USING C++ Write a program to practice how to use length(), find() and substr() f
ID: 3873208 • Letter: U
Question
USING C++
Write a program to practice how to use length(), find() and substr() funcitons. You should understand the first exercise before you try this one.
Follow the steps below:
Declare a string variable: OriginalString.
Assign "And now for something completely different." to OriginalString.
Display the length of OriginalString.
Find and display the position of "completely" in the OriginalString.
Declare a string variable: NewString.
Use the substr() function to get this sub-string of OriginalString: "And now for something ".
then assign it to NewString.
Output NewString.
Get a sub-string of OriginalString with value "different.".
Add this substring to NewString.
Display NewString. The output should look like this:
And now for something different.
Compile and run this C++ program.
Show your lab instructor the program output.
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string OriginalString="And now for something completely different.";
cout<<"The length of the original string is "<< OriginalString.length();
size_t pos = OriginalString.find("completely"); // position of "completely" in OriginalString
cout<<" Position of the completely is "<<pos;
int pos1 = OriginalString.find("And now for something");
string str=OriginalString.substr (pos1);
int pos2 = OriginalString.find("different");
str+=OriginalString.substr (pos2);
cout<<" New String is "<<str;
return 0;
}
Output:
The length of the original string is 43
Position of the completely is 22
New String is And now for something completely.
New String is And now for something completely different.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.