Question

C++ Programming Question: This programming assignment is intended to demonstrate your knowledge of the following: ▪...

C++ Programming Question:

This programming assignment is intended to demonstrate your knowledge of the following:

▪ Writing a while loop

▪ Write functions and calling functions

Text Processing [50 points]

We would like to demonstrate our ability to control strings and use methods. There are times when a program has to search for and replace certain characters in a string with other characters. This program will look for an individual character, called the key character, inside a target string. It will then perform various functions such as replacing the key character with an asterisk (*) wherever it occurs in the target string. For example, if the key character were

'a'

and the string were

"He who laughs last, laughs fast, faster, FASTEST."

then the operation of replacing the 'a' by an asterisk would result in the new string:

"He who l*ughs l*st, l*ughs f*st, f*ster, FASTEST."

As you can see, only the lower-case 'a' was detected and replaced. This is called "case-sensitivity" and this entire program spec is case-sensitive. This was only one possible task we might perform. Another would be to remove all instances of the key character rather than replace each with an asterisk. Yet a third might be to count the number of key characters. We are going to do it all.

Modifying vs. Rebuilding

Whenever we deal with strings, we have to decide whether we are going to modify an existing string or create a second string which has the desired changes. We will not attempt to touch the original string in our operations. Instead, we will declare a new string object and build that up in stages, replacing or removing the desired characters of the original string by simply taking action on the new string we are building. When I say we "build" a string, I mean that we initialize the string to be empty, "", and then use concatenation to replace it with ever-longer versions of itself. This technique has some advantages that allow it to be used for a variety of purposes, so it's good to learn now. For example, consider this statement, which appends an exclamation point to the end of a string,

myStr: myStr = myStr + "!";

This statement uses the old value of myStr on the RHS, then completely throws away the old value on the LHS and replaces it with the new, longer, string. This is similar to a more familiar kind of numeric statement:

n = n + 3;

where we replace the old contents of n with new contents.

The Methods

We will be writing methods. Some will get input from the user (which take no parameters) and others will take arguments: the string and/or key character. Depending on the method we write, it will return one of the following types: a string, a char or an int. For example, one of the methods we write will take the key character and the target string as parameters and will return a new string which has all the occurrences of the key character replaced by asterisks. Its signature would look like this:

string maskCharacter(string theString, char keyCharacter)

We will be careful at all stages: input methods will only deal with user input, and not attempt to do computation. Computations will not do any input or output. The exception is always main(). In main() we may do input and output directly if we are not required to use a method to do so by the spec. In our spec, this week, we will use input methods to get the input (not main()), but we will allow main() to do the output directly.

The Program Spec Ask the user to enter both a key character and a target string (phrase, sentence, etc.). Then, show the user three things::

1. The target string with the key character replaced by asterisks.

2. The target string with the key character removed.

3. The number of occurrences of the key character (case sensitive) in the target string.

This program does not loop for different strings. Once it processes a string, the program ends. Here, "character" means any printable character. They can be letters, numbers or even special symbols. Each target input string should be complex with a mix of characters, special symbols, numbers to show how the program handles each category.

Input Method Specs

1. char getKeyCharacter()

This method requests a single character from the user and continues to ask for it until the user gets it right: this method will test to make sure the user only types one single character. 0, 2, 3 or more characters will be flagged as an error and the method will keep at the user until he types just one character. You are not required to use a char as an input variable -- in fact, you cannot solve the problem using a char as input (you must think about this and make the appropriate choice here). What matters is that a char is returned, as a functional return, to the client, main().

2. String getString()

This method requests a string from the user and continues to ask for it until the user gets it right: this method will test to make sure the user only types a string that has at least 4 characters. Make this minimum size a constant (const), and use that symbolic constant, not the literal (4) wherever it is needed. The acquired string will be returned as a functional return.

Processing Method Specs

You must write the methods below from scratch (based on the few available tools that I mention in the modules and the links to the allowable character and string methods provided in the module page "A Nice Example" ). Do not rely on any other built-in or pre-existing methods that appear to provide any of this functionality for you. There is a high value to you in practicing such logic. ‘

1. String maskCharacter(String theString, char keyCharacter)

This method will take both a string and a character as parameters and return a new string that has each occurrence of the key character replaced by an asterisk, '*'.

2. String removeCharacter(String theString, char keyCharacter)

This method will take both a string and a character as parameters, and return the number of key characters that appear in the string (case sensitive).

3. int countKey(String theString, char keyCharacter)

This method will take both a string and a character as parameters, and return the number of key characters that appear in the string (case sensitive).

Input Errors

Whenever the user makes an input error, keep at them until they get it right. Do not return from an input method until you have acquired a legal value, even if it takes years.

Test Run Requirements:

Submit at least three runs. In at least one of the three runs, intentionally commit input errors to demonstrate both kinds of illegal input described above. Your program should be called TextProcessing.cpp

Sample Run

Please enter a SINGLE character to act as key: sdfs

Please enter a SINGLE character to act as key:

Please enter a SINGLE character to act as key: d

Please enter a phrase or sentence >= 4 and <= 500 characters:

Please enter a phrase or sentence >= 4 and <= 500 characters: ' '

Please enter a phrase or sentence >= 4 and <= 500 characters: sdf sdaf ASDF ASDF sdf sdf (*j ljsdf

String with key character, 'd' masked:

s*f s*af ASDF ASDF s*f s*f (*j ljs*f

String with 'd' removed:

sf saf ASDF ASDF sf sf (*j ljsf

# of occurrences of key character, 'd': 5

Press any key to continue . . .

(MORE RUNS REQUIRED BY STUDENT)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// C++ program to perform string manipulation

#include <iostream>

using namespace std;

// function declaration

char getKeyCharacter();

string getString();

string maskCharacter(string theString, char keyCharacter);

string removeCharacter(string theString, char keyCharacter);

int countKey(string theString, char keyCharacter);

int main() {

       char key;

       string phrase;

       key = getKeyCharacter();

       phrase = getString();

       cout<<"String with key character, '"<<key<<"' masked:"<<endl;

       cout<<maskCharacter(phrase,key)<<endl;

       cout<<"String with '"<<key<<"' removed:"<<endl;

       cout<<removeCharacter(phrase,key)<<endl;

       cout<<"# of occurrences of key character, '"<<key<<"':"<<countKey(phrase,key)<<endl;

       return 0;

}

// function that requests a single character from the user and continues to ask for it until the user gets it right

char getKeyCharacter()

{

       string charInput;

       // input

       cout<<"Please enter a SINGLE character to act as key: ";

       getline(cin,charInput);

       // check if the input is one character , since getline accepts the ending '\n' in the string, we subtract 1 from the length

       // loop that continues till we get as input a character

       while((charInput.length()-1 == 0) || (charInput.length()-1 > 1))

       {

             cout<<"Please enter a SINGLE character to act as key: ";

             getline(cin,charInput);

       }

       return charInput.at(0);

}

// function that requests a string from the user and continues to ask for it until the user gets it right

string getString()

{

       string phrase;

       // input of phrase

       cout<<"Please enter a phrase or sentence >= 4 and <= 500 characters: ";

       getline(cin,phrase);

       // validate that the phrase is between [4,500] characters

       while(((phrase.length()-1) < 4) || ((phrase.length()-1) > 500))

       {

             cout<<"Please enter a phrase or sentence >= 4 and <= 500 characters: ";

             getline(cin,phrase);

       }

       return phrase;

}

// function that will take both a string and a character as parameters

// and return a new string that has each occurrence of the key character replaced by an asterisk, '*'.

string maskCharacter(string theString, char keyCharacter)

{

       string maskString="";

       // loop over the string and replace the key character with an '*'

       for(unsigned int i=0;i<theString.length();i++)

       {

             if(theString.at(i) == keyCharacter)

             {

                    maskString += '*';

             }else

                    maskString += theString.at(i);

       }

       return maskString;

}

// function that will take both a string and a character as parameters,

// and return the number of key characters that appear in the string (case sensitive).

string removeCharacter(string theString, char keyCharacter)

{

       string removeString="";

       // loop over the string , removing the key character

       for(unsigned int i=0;i<theString.length();i++)

       {

             if(theString.at(i) != keyCharacter)

             {

                    removeString += theString.at(i);

             }

       }

       return removeString;

}

// function that will take both a string and a character as parameters,

// and return the number of key characters that appear in the string (case sensitive).

int countKey(string theString, char keyCharacter)

{

       int count = 0;

       // loop over the string, counting the number of times key character occurs in the string

       for(unsigned int i=0;i<theString.length();i++)

       {

             if(theString.at(i) == keyCharacter)

             {

                    count++;

             }

       }

       return count;

}

//end of program

Output:

Add a comment
Know the answer?
Add Answer to:
C++ Programming Question: This programming assignment is intended to demonstrate your knowledge of the following: ▪...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Assignment Overview This programming assignment is intended to demonstrate your knowledge of the following:  Writing...

    Assignment Overview This programming assignment is intended to demonstrate your knowledge of the following:  Writing a while loop  Writing a for loop  Writing a while loop with a sentinel value Chocolate Coupons Foothill Fro-cho, LLC, gives customers a coupon every time they purchase a chocolate bar. After they earn a certain number of coupons, they qualify for a free chocolate bar, which they may use toward the purchase of a single chocolate bar. Usually, 7 is the...

  • JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information...

    JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information being exposed, it is becoming more and more important to find ways to protect our sensitive data. In this program we will develop a simple tool that helps users generate strong passwords, encrypt and decrypt data using some cyphering techniques. You will need to create two classes. The first class is your driver for the application and contains the main method. Name this class...

  • Intro to Programming in C – Large Program 1 – Character/ Number converter Assignment Purpose: To...

    Intro to Programming in C – Large Program 1 – Character/ Number converter Assignment Purpose: To compile, build, and execute an interactive program with a simple loop, conditions, user defined functions and library functions from stdio.h and ctype.h. You will write a program that will convert characters to integers and integers to characters General Requirements • In your program you will change each letter entered by the user to both uppercase AND lowercase– o Use the function toupper in #include...

  • JAVA public static String generatePassword(String gp)        {            String password="";       ...

    JAVA public static String generatePassword(String gp)        {            String password="";            boolean b= false;            for (int i =0;i            {                char ch = gp.charAt(i);                if (i == 0)                {                    password += Character.toUpperCase(ch);                }                if (ch == 'S' || ch == 's')           ...

  • Write in C Spring 2016 Lab Assignment 11 ET2100 In computer programming in general a "string"...

    Write in C Spring 2016 Lab Assignment 11 ET2100 In computer programming in general a "string" is a sequence of characters. In the C language anything within double quotes is a "string constant" so you have been seeing strings all semester. But we can also have string variables. In the C language these are implemented as an array of char, e.g. char name (10]: In order to make these variables easier to work with, it has been universally agreed that...

  • 14.3: More Sentences Write a program that allows a user to enter a sentence and then...

    14.3: More Sentences Write a program that allows a user to enter a sentence and then the position of two characters in the sentence. The program should then report whether the two characters are identical or different. When the two characters are identical, the program should display the message: <char> and <char> are identical! Note that <char> should be replaced with the characters from the String. See example output below for more information. When the two characters are different, the...

  • IN C language Write a C program that prompts the user to enter a line of...

    IN C language Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr andcreadLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate...

  • c++ pleased Assignment 6a (15 points] - Character and String related processing... Listed below are two...

    c++ pleased Assignment 6a (15 points] - Character and String related processing... Listed below are two interesting programming challenges that will require a bit of character and/or string related processing with functions. (Carefully read the specifications for each programming challenge and select ONE.) (1) Sum of Digits in a String Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. Read the input as a C-string or a string object. The program...

  • The following question is for C programming. There is a function that has the header char...

    The following question is for C programming. There is a function that has the header char * decodeSubstitution(char * lcEncodingKey, char * src, char *dest) What it ultimately is supposed to do is take an encoded array of characters (src), decode it and put it into dest, and return the decoded array of characters. The first step, however, is what I need help with. The first step is to create the decoding key called lcDecodingKey using the encoding key was...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT