#include <Windows.h>
#include <iostream.h>
TCHAR * ReverseStr(TCHAR * src,int n)//將字符串的前n個字符翻轉
{
int len = strlen(src);
if(src == NULL || n < 1)
return NULL;
n = (n > len ? len : n);
int m = n / 2;
TCHAR Tmp;
for(int i = 0 ; i < m ; i++ ,n--)
{
Tmp = src[i];
src[i] = src[n-1] ;
src[n-1] = Tmp;
}
return src;
}
char* LeftRotateStr(char * src,int n) //將字符串的前n個字符原序放到最後
{
int len = strlen(src);
if(src == NULL || n < 1 || len < n)
return NULL;
ReverseStr(src,n);
ReverseStr(&src[n],len - n);
ReverseStr(src,len);
return src;
}
char * RotateSentence(char *src)//反序輸出所有的單詞,比如 “I love this game”輸出爲“game this love I”。經典的面試題
{
int len = strlen(src);
if(src == NULL || len < 1) return NULL;
int wordlen = 0;
int i=0 , j = 0;
for( i = 0; i <= len ; i++)
{
if(src[i] == ' ' || src[i] == '\0')
{
ReverseStr(&src[j],wordlen);
j = i + 1;
wordlen = -1;
}
wordlen++;
}
ReverseStr(src,len);
return src;
}
int main()
{
char str[]="123456789";
cout<<endl;
cout<<str<<endl;
ReverseStr(str,5);
cout<<str<<endl;
cout<<str<<endl;
LeftRotateStr(str,8);
cout<<str<<endl;
char str2[]="I love the stupid game ";
cout<<str2<<endl;
RotateSentence(str2);
cout<<str2<<endl;
}
經典的字符串操作的題目,左旋轉,反序輸出所有的單詞
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.