Problem description: Write a program that (1) reads a string, (2) replaces every
ID: 3541386 • Letter: P
Question
Problem description: Write a program that (1) reads a string,
(2) replaces every occurrence of the substring "C++" by a string "Java",
(3) converts every alphabet in the string to upper case, and
(4) output the final string.
For example, if the input is:
I love C++! C++ is fun.
after replacing "C++" by "Java", it becomes
I love Java! Java is fun.
after converting each alphabet to upper case, it becomes
I LOVE JAVA! JAVA IS FUN.
You are only allowed to call the following string functions:
length: get the number of chars in the string
substr: get a specified substring
find: find the position of a substring
[]: accessing a char at a specific position in the string.
In other words, a string can be viewed and accessed as an array of chars.
str1 = str2; copy the string str2 to the string str1
str = str1 + str2; concatenate str1 and str2, and save it to str.
*/
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string original; //contains input string
string modified; //the string obtained by replacing "C++" with "Java"
string upperStr; //convert chars in the string "modified" to upper case
int pos; //the starting position of the substr "C++"
getline(cin, original);
Write a code segment that (1) copy the string to modified and upperStr, (2) replaces every occurrence of the substring "C++" by a string "Java", (3) converts every alphabet in the string to upper case, and (4) output the final strings. (this step is done already)
cout << "The original string is: " << original << endl
<< "After replacing C++ with Java: " << modified << endl
<< "Converting to upper case: " << upperStr << endl;
return 0;
}
Explanation / Answer
please rate - thanks
add to add variable i and pos2 - hope that's OK
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string original; //contains input string
string modified; //the string obtained by replacing "C++" with "Java"
string upperStr; //convert chars in the string "modified" to upper case
int pos; //the starting position of the substr "C++"
int pos2;
modified="";
upperStr="";
pos=0;
getline(cin, original);
pos2=original.find("C++",pos);
while(pos2<original.length())
{modified=modified+original.substr(pos,pos2-pos)+"JAVA";
pos=pos2+3;
pos2=original.find("C++",pos);
}
modified=modified+original.substr(pos,original.length());
upperStr=modified;
for(int i=0;i<upperStr.length();i++)
if(upperStr[i]>=97&&upperStr[i]<=122)
upperStr[i]-=32;
cout << "The original string is: " << original << endl
<< "After replacing C++ with Java: " << modified << endl
<< "Converting to upper case: " << upperStr << endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.