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,
#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";
}
Comments
Leave a comment