输入字符串,逆序输出(两种方法) |
您所在的位置:网站首页 › 逆序排列输出 › 输入字符串,逆序输出(两种方法) |
问题描述
从键盘上输入一组字符串,实现逆序输出。 解题思路方法一:输出的时候从(n-1)的数据往前依次输出。 方法二:假设输入n个字符,字符串默认末尾补上' \0 ',将第0个字符和第(n-1)个字符交换,依次交换中间的数据 输入的数据 HELLO\0第1次交换后的数据 OELLH\0第(n-1)次交换后的数据 OLLEH\0第一种方法 #include #include #define N 20 int main(int argc, const char *argv[]) { char str[N] = "\0"; int i, n; printf("Please input a String:"); gets(str); // n = sizeof(str) / sizeof(char); n = strlen(str); for(i = n-1; i >= 0; i--) putchar(str[i]); putchar('\n'); return 0; }第二种方法 #include #include #define N 20 int main(int argc, const char *argv[]) { char str[N] = "\0"; int i, j, n,ch; printf("Please input a String:"); gets(str); n = strlen(str); //获取字符串的长度 i = 0; j = n-1; while(i < j){ ch = str[i]; str[i] = str[j]; str[j] = ch; i++; j--; } puts(str); return 0; }结果:
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |