Expand|Select|Wrap|Line Numbers
- #include<iostream>
- #include<cstring>
- #include<cstdlib>
- using namespace std;
- int main()
- {
- cout<<"Transposing letters in a string \n";
- cout<<"Type a short sentence (end with Ctrl+Z)"<<endl;
- char s[81]={0};
- int count=0;
- do
- {
- cin.getline(s,81);
- //if(*s)cout<<s; //this prints the sentence correctly
- }while(*s);
- for(int i=0;i<sizeof(s);i++)
- {
- cout<<s[i];
- if(s[i]==' ')count++;
- }
- cout<<"\nThere are "<<count<<" words in the sentence\n";
- char *p1=&s[0]; //set both pointers to 1st letter
- char *p2=&s[0];
- while(*p2>='a' && *p2<='z' || *p2>='A' && *p2<='Z' )
- { p2++; } // advance p2 to end of 1st word
- if(*p2==' ')
- p2--;
- swap(*p1,*p2);
- for(int i=0;i<count;i++)//remaining words
- { p2+=2; //position p2 on 1st letter of next word
- p1=p2 ; // move p1 to same position
- while(*p2>='a' && *p2<='z' && *p2!='\n')
- { p2++; } // advance p2 to end of next word
- if(*p2==' ')p2--;//if it goes to space..bring back one
- swap(*p1,*p2);
- }
- cout<<"After swapping, the string becomes: \n";
- for(int i=0;i<sizeof(s);i++)
- {
- cout<<s[i];
- }
- cout<<"\n\n";
- char q;
- cout<<"Press any key to continue...";
- cin>>q;
- return 0;
- }
Transposing letters in a string
Type a short sentence (end with Ctrl+Z)
Swapping the first and last letter in each word ^Z
wapping the first and last letter in each word
There are 9 words in the sentence
After swapping the string becomes:
wgppina eht tirsf dna tasl rettel ni hace dorw
Press any key to continue...
*/