C 练习实例35
题目:字符串反转,如将字符串 "www.facesoho.com" 反转为 "moc.boonur.www"。
程序分析:无。
实例
// Created by www.facesoho.com 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[] = "www.facesoho.com";
printf("'%s' =>\n", s);
reverse(s); // 反转字符串
printf("'%s'\n", s);
return 0;
}
以上实例输出结果为:
'www.facesoho.com' => 'moc.boonur.www'

文人墨客
利用指针实现:
#include <stdio.h> //题目:字符串反转,如将字符串 "www.facesho.com" 反转为"moc.boonur.www"。 void reverse(char *str); int main() { char str[100]; printf("输入字符串:"); fgets(str, sizeof str, stdin); reverse(str); printf("逆序后:%s\n",str); return 0; } void reverse(char *str) { char *p = str, strNew[100]; int i = 0; while (str[i] != '\n') { strNew[i] = str[i]; ++i; } strNew[i] = '\0';//把原字符串末尾置'\0' while (*p != '\n') *(p++) = strNew[--i];//把原字符逆序 *p = '\0';//逆序后末尾置'\0' }文人墨客
参考方法:
#include<stdio.h> #include<string.h> #include<stdlib.h> void reverse(char *p,int n); int main() { char *a; a=(char *)malloc(sizeof(char)); printf("请输入字符串:"); //gets(a); fgets(a, (sizeof a / sizeof a[0]), stdin); reverse(a,strlen(a)); } void reverse(char *p,int n) { while(n) { printf("%c",*(p+n-1)); n--; } }文人墨客
参考方法:
#include<stdio.h> #include<string.h> void reverse(char str[], int lenth) { int i = 1, tmp = lenth; for(i = 1; i <= lenth / 2; i++) { *str ^= *(str + tmp - 1); *(str + tmp - 1) ^= *str; *str ^= *(str + tmp - 1); str++; tmp -= 2; } } int main() { char str[100] = {0}; printf("请输入一个字符串:"); //fgets(str, 100, stdin); scanf("%s", str); reverse(str, strlen(str)); printf("%s\n",str); return 0; }文人墨客
参考方法:
#include<stdio.h> #include<string.h> #define N 80 void reverse(char *str) { int j = strlen(str); int i = 0; j--; while(i < j) { char temp; temp = str[i]; str[i] = str[j]; str[j] = temp; i++; j--; } } int main(void) { char str[N]; memset(str,'\0',sizeof(str)); gets(str); reverse(str); puts(str); return 0; }文人墨客
参考方法:
#include <stdio.h> #include <string.h> int main() { char s[128] = {0}, s1[128] = {0}; int i, j = 0; printf("请输入字符串:"); gets(s); for (i = strlen(s) - 1; i >= 0; i--) { s1[j++] = s[i]; } puts(s); puts(s1); return 0; }文人墨客
参考方法:
#include<stdio.h> #include<string.h> void reverse(char *str) { int len; char tmp; char *begin,*end; len=strlen(str); //获取字符串长度] begin=str; //指针begin指向字符串首地址 end=str+len-1; //指针end指向字符串尾地址 while(begin<end) { tmp=*begin; *begin=*end; *end=tmp; begin++; end--; } } int main() { char string[]="www.facesho.com"; reverse(string); puts(string); return 0; }文人墨客
参考解法:
#include <stdio.h> #include<string.h> int main() { char c[1000]; fgets(c, (sizeof c / sizeof c[0]), stdin); int d=strlen(c); //printf("%d\n",d); char a[1000]; int j=0; for(int i=d-1;i>=0;i--) { a[i]=c[j]; j++; } puts(a); }