Answer to Question #280807 in C++ for mano

Question #280807

The following pseudocode describes how to swap two letters in a word. We are given a string str and two positions i and j. (i comes before j) Set first to the substring from the start of the string to the last position before i. Set middle to the substring from positions i + 1 to j - 1. Set last to the substring from position j + 1 to the end of the string. Concatenate the following five strings: first, the string containing just the character at position j, middle, the string containing just the character at position i, and last. Check this pseudocode, using the string "Gateway" and positions 2 and 4. Draw a diagram of the string that is being computed,


1
Expert's answer
2021-12-17T06:51:42-0500
#include<iostream>
#include<string>

using namespace std;

int main()
{
	string str="Gateway";
	int i=2;
	int j=4;
	cout<<"String \""<<str<<"\"";
	string first=str.substr(0,i);
	string middle=str.substr(i+1,j-i-1);
	string last=str.substr(j+1);
	char strI=str[i];
	char strJ=str[j];
	str=first+strJ+middle+strI+last;
	cout<<" with two swapped letters is \""<<str<<"\"";
	cout<<"\nDiagram of string \""<<str<<"\":\n";
	for(int k=str.size();k>0;k--)
	{
		if(first.size()>=k)
			cout<<"#";
		if(k==1)
			cout<<"\t#";
		else
			cout<<"\t";
		if(middle.size()>=k)
			cout<<"\t#";
		else
			cout<<"\t";
		if(k==1)
			cout<<"\t#";
		else
			cout<<"\t";
		if(last.size()>=k)
			cout<<"\t#";
		if(k<str.size()/2)
			cout<<endl;
	}
	cout<<"\nfirst\tj\tmiddle\ti\tlast";
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog