#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void resort(char s[]) //或者是resort(char *s)
{
char temp;
for (int i=0,j=strlen(s)-1;i<j;i++,j--) //对j的初始化是关键
{
temp=s[i];s[i]=s[j];s[j]=temp;
}
}
int main()
{
char s1[]="this is a dog";
cout<<strlen(s1)<<endl; //求string中元素个数
cout<<s1<<endl; //之前的的字符串
resort(s1);
cout<<s1<<endl; //颠倒后的字符串
return 0;
}PS:注意区分sizeof,strlen()和.size()的区别。3-1 编写并测试一个函数,逆转字符串中字符顺序
最新推荐文章于 2021-11-11 15:46:05 发布
本文介绍了一段使用C++编程语言实现的字符串颠倒功能的代码,通过定义一个函数`resort`来实现字符串的字符顺序反转,并通过实例展示了如何调用此函数并输出颠倒前后的字符串。
398

被折叠的 条评论
为什么被折叠?



