給定一字串,將每個單詞的字元順序倒置,單詞間的順序不變。例如:輸入字串“I love you”,輸出“I evol uoy”。
阿新 • • 發佈:2019-02-04
#include <iostream>
#include <sstream>
using namespace std;
//計算並返回字串長度
int Length(char *str)
{
int length=0;
while((*str++)!='\0')
length++;
return length;
}
//對單個單詞字元反轉
void _Reverse(char *str,int low,int high)
{
char tempChar;
while(low<high)
{
tempChar=str[low];
str[low]=str[high];
str[high]=tempChar;
low++;
high--;
}
}
//利用字串流讀取每個單詞並將其反轉,單詞間有多個空格時合併為一個
void Reverse(char *str)
{
istringstream in(str);
int length;
for(string s;in>>s;)
{
length=Length(&s[0]);
_Reverse(&s[0],0,length-1);
cout<<s<<" ";
}
}
//反轉的另一個方法,直接對原字串操作
void ReverseVer2(char *str)
{
int low,high;
int length=Length(str);
for(int i=0;i<=length;i++)
{
if(i==0&&str[i]!='\40')
{
low=i;
continue;
}
if(str[i]!='\40'&&str[i-1]=='\40')
{
low=i;
continue;
}
if(str[i]=='\40'||str[i]=='\0')
{
high=i-1;
_Reverse(str,low,high);
}
}
}
int main()
{
char str[]="I love you";
cout<<"first method:";
Reverse(str);
cout<<endl;
ReverseVer2(str);
cout<<"second method:"<<str<<endl;
return 0;
}
#include <sstream>
using namespace std;
//計算並返回字串長度
int Length(char *str)
{
int length=0;
while((*str++)!='\0')
length++;
return length;
}
//對單個單詞字元反轉
void _Reverse(char *str,int low,int high)
{
char tempChar;
while(low<high)
{
tempChar=str[low];
str[low]=str[high];
str[high]=tempChar;
low++;
high--;
}
}
//利用字串流讀取每個單詞並將其反轉,單詞間有多個空格時合併為一個
void Reverse(char *str)
{
istringstream in(str);
int length;
for(string s;in>>s;)
{
length=Length(&s[0]);
_Reverse(&s[0],0,length-1);
cout<<s<<" ";
}
}
//反轉的另一個方法,直接對原字串操作
void ReverseVer2(char *str)
{
int low,high;
int length=Length(str);
for(int i=0;i<=length;i++)
{
if(i==0&&str[i]!='\40')
{
low=i;
continue;
}
if(str[i]!='\40'&&str[i-1]=='\40')
{
low=i;
continue;
}
if(str[i]=='\40'||str[i]=='\0')
{
high=i-1;
_Reverse(str,low,high);
}
}
}
int main()
{
char str[]="I love you";
cout<<"first method:";
Reverse(str);
cout<<endl;
ReverseVer2(str);
cout<<"second method:"<<str<<endl;
return 0;
}