#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;
}
经典的字符串操作的题目,左旋转,反序输出所有的单词
最新推荐文章于 2022-07-13 23:58:13 发布