Given a string on one line, a second string on a second line, and an integer index, insert the contents of the second string in the first string at the index specified. Then, output the result.
Ex: If the input is:
FuzzyBear
Wuzzy
5
the output is:
FuzzyWuzzyBear
Note: Using a pre-defined string function, the solution can be just one line of code.
#include <iostream>
#include <string>
using namespace std;
int main() {
string workStr;
string otherStr;
int strPos;
getline(cin, workStr);
getline(cin, otherStr);
cin >> strPos;
cout << workStr << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string workStr = "Fuzzy";
string otherStr = "Wuzzy";
int strPos=2,i,l=0;
cout<<"\n\tString-1: "; getline(cin, workStr);
cout<<"\n\tString-2: "; getline(cin, otherStr);
strPos=-1;
while(strPos<0 || strPos>workStr.size())
{
cout<<"\n\tEnter Pos. (0 to "<<workStr.size()<<") : "; cin>>strPos;
}
char temp[workStr.size()+otherStr.size()];
for(i=0;i<(workStr.size() + otherStr.size());i++) temp[i]=0x20;
if(strPos<=workStr.size())
{
for(i=0;i<strPos;i++) {temp[i] = workStr[i]; l++;}
int j=0;
for(i=strPos;i<(strPos+otherStr.size());i++){temp[i]=otherStr[j]; j++; l++;}
for(i=strPos;i<workStr.size();i++) temp[l] = workStr[i];
}
cout<<"\nNew String: ";
for(i=0;i<(workStr.size() + otherStr.size());i++) cout<<temp[i];
return 0;
}
Comments
Leave a comment