首页 > 学院 > 开发设计 > 正文

字符串逆序

2019-11-14 12:40:29
字体:
来源:转载
供稿:网友

1、普通逆序 # include< stdio.h> # include < stdlib.h> # include < string.h>

int main() { char str[100]; gets(str); int i = 0; char ch; int len = strlen(str); for(i = 0; i < len / 2; i++) { ch = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = ch; } puts(str); return 0; }

2、将字符串中的单词逆序 #include < stdio.h> #include < string.h> int main() { char str[100] = {0}; int len = 0; int count = 0; int index = 0; char ch = 0; int begin = 0, end = 0; int i = 0; int spaceNumbers = 0;

/* 得到输入的字符串 */ gets(str); len = strlen(str);

for(index = 0; index < len; index++) { if(str[index] == ’ ‘) { end = index; for(i = 0; i < count/2; i++) { ch = str[begin+i]; str[begin+i] = str[end-1-i]; str[end-1-i] = ch; } begin = end+1; count = 0; spaceNumbers++; }

/* 说明到字符串的结尾了 */ if(index == len-1) { end = len; for(i = 0; i < count/2; i++) { ch = str[begin+i]; str[begin+i] = str[end-1-i]; str[end-1-i] = ch; } } count++; } PRintf(“%s/n”,str); return 0; }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表