Created
March 2, 2010 12:06
-
-
Save shaobin0604/319466 to your computer and use it in GitHub Desktop.
反转单词
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| #define true 1 | |
| #define false 0 | |
| typedef int bool; | |
| void reverse_sentence(char str[]); | |
| void reverse_string(char str[], int start, int end); | |
| bool reserse_sentence_1(char str[]); | |
| int main(int argc, char* argv[]) | |
| { | |
| char str[] = "abc def ghi jkl "; | |
| printf("before --> %s\n", str); | |
| reverse_sentence_1(str); | |
| printf("after 1--> %s\n", str); | |
| reverse_sentence(str); | |
| printf("after 2--> %s\n", str); | |
| return 0; | |
| } | |
| bool reverse_sentence_1(char str[]) | |
| { | |
| int len = strlen(str); | |
| int pos = len - 1; | |
| int word_start; | |
| int word_end; | |
| int write_pos = 0; | |
| char* buf = (char*)malloc(len + 1); | |
| if (buf == NULL) | |
| return false; | |
| while (pos >= 0) | |
| { | |
| if (str[pos] == ' ') | |
| { | |
| buf[write_pos++] = ' '; | |
| } | |
| else | |
| { | |
| word_end = pos; | |
| while (pos >= 0 && str[pos] != ' ') | |
| pos--; | |
| pos++; | |
| word_start = pos; | |
| while (word_start <= word_end) | |
| { | |
| buf[write_pos++] = str[word_start++]; | |
| } | |
| } | |
| pos--; | |
| } | |
| buf[write_pos] = '\0'; | |
| strcpy(str, buf); | |
| free(buf); | |
| return true; | |
| } | |
| void reverse_string(char str[], int start, int end) | |
| { | |
| while (start < end) | |
| { | |
| char c = str[start]; | |
| str[start] = str[end]; | |
| str[end] = c; | |
| start++; | |
| end--; | |
| } | |
| } | |
| void reverse_sentence(char str[]) | |
| { | |
| int len = strlen(str); | |
| int word_start, pos; | |
| reverse_string(str, 0, len - 1); | |
| for (pos = 0; pos < len; pos++) | |
| { | |
| if (str[pos] != ' ') | |
| { | |
| word_start = pos; | |
| while (pos < len && | |
| str[pos] != ' ') | |
| pos++; | |
| pos--; | |
| reverse_string(str, word_start, pos); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment