这道题可分为两步:第一步将整个字符串全部倒置:!anihC morf ma I
第二步部分倒置,如果不是空格,则倒置单词
#include <stdio.h> #include <string.h> int main() { int i = 0,j = 0; int begin = 0,end = 0; char str[] = "I am from China!",tmp; //char tmp; printf("--1--:str = %s\n",str); //第一步:全部翻转 j = strlen(str) - 1; while(j > i) { tmp = str[i]; str[i] = str[j]; str[j] = tmp; j--; i++; } printf("--2--:str = %s\n",str); //第二步:将每个空格隔开的单词翻转 i = 0; //i = 0不能丢,要从头开始 while(str[i]) { if(str[i] != ' ') { begin = i; while(str[i] && str[i] != ' ') { i++; } i = i - 1; end = i; } while(end > begin) { tmp = str[begin]; str[begin] = str[end]; str[end] = tmp; end--; begin++; } i++; } printf("--3--:str = %s\n",str); return 0; }原文链接:https://www.f2er.com/javaschema/283663.html