C 练习实例35 – 字符串反转
最后更新于:2022-03-27 01:30:55
C 练习实例35
题目:字符串反转,如将字符串 “docs.gechiui.com/w3school” 反转为 “moc.boonur.www”。
程序分析:无。
实例
// Created by docs.gechiui.com/w3school on 15/11/9.
// Copyright © 2015年 菜鸟教程. All rights reserved.
// #include <stdio.h> void reverse(char* s)
{
// 获取字符串长度
int len = 0;
char* p = s;
while (*p != 0)
{
len++;
p++;
}
int i = 0;
char c;
while (i <= len / 2 – 1)
{
c = *(s + i);
*(s + i) = *(s + len – 1 – i);
*(s + len – 1 – i) = c;
i++;
}
} int main()
{
char s[] = "docs.gechiui.com/w3school";
printf("‘%s’ =>\n", s);
reverse(s); // 反转字符串
printf("‘%s’\n", s);
return 0;
}
// Copyright © 2015年 菜鸟教程. All rights reserved.
// #include <stdio.h> void reverse(char* s)
{
// 获取字符串长度
int len = 0;
char* p = s;
while (*p != 0)
{
len++;
p++;
}
// 交换 …
int i = 0;
char c;
while (i <= len / 2 – 1)
{
c = *(s + i);
*(s + i) = *(s + len – 1 – i);
*(s + len – 1 – i) = c;
i++;
}
} int main()
{
char s[] = "docs.gechiui.com/w3school";
printf("‘%s’ =>\n", s);
reverse(s); // 反转字符串
printf("‘%s’\n", s);
return 0;
}
以上实例输出结果为:
'docs.gechiui.com/w3school' => 'moc.boonur.www'