首页 > 代码库 > 反转句子中单词的顺序(单词中字符的顺序保持不变,c语言)
反转句子中单词的顺序(单词中字符的顺序保持不变,c语言)
1 #include <stdio.h> 2 #include <string.h> 3 4 void exchange(char *string, int c1, int c2); 5 void revertString(char *string, int iStart, int iEnd); 6 void revertWordsInString(char *string); 7 8 int main(int argc, const char * argv[]) 9 { 10 11 // insert code here... 12 printf("Begin>>>!\n"); 13 14 char originalString[100] = "abcdef"; 15 printf("%s\n", originalString); 16 size_t len = strlen(originalString); 17 revertString(originalString, 0, (int)(len-1)); 18 printf("%s\n", originalString); 19 20 char string[100] = "I am a student coming from XX"; 21 printf("%s\n", string); 22 revertWordsInString(string); 23 printf("%s\n", string); 24 25 26 return 0; 27 } 28 29 void revertString(char *string, int iStart, int iEnd) 30 { 31 while (iStart < iEnd) { 32 exchange(string, iStart, iEnd); 33 iStart++; 34 iEnd--; 35 } 36 } 37 38 void exchange(char *string, int c1, int c2) 39 { 40 char tmp = string[c1]; 41 string[c1] = string[c2]; 42 string[c2] = tmp; 43 } 44 45 void revertWordsInString(char *string) 46 { 47 size_t len = strlen(string); 48 int indexEnd = (int)len - 1; 49 int i = 0; 50 int j = 0; 51 while (j < indexEnd) { 52 while (*(string + j) != ‘ ‘) { 53 j++; 54 if (j >= indexEnd) { 55 break; 56 } 57 } 58 if (j < indexEnd) { 59 revertString(string, i, j-1); 60 j++; 61 i = j; 62 } 63 } 64 revertString(string, i, j); 65 revertString(string, 0, indexEnd); 66 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。