单词的反转
刷题,求单词的翻转。
利用到了编程珠玑上的翻手法则。
主要思路是先将字符串整体翻转,再在单词内部翻转(先单词翻转,在整体翻转貌似也行)。
#include <stdio.h> #include <string.h> #include <algorithm> char* string_reverse(char* first, char* last) { char* ptr = first; while (first < last) { std::iter_swap(first++, --last); } return ptr; } char* string_word_reverse(char* first, char* last, const char sep_char) { if (first >= last) { return NULL; } string_reverse(first, last); printf("in %s\n", first); char* head_ptr = first; char* sep_ptr = first; while (first < last) { sep_ptr = strchr(first, sep_char); if (!sep_ptr) { break; } string_reverse(first, sep_ptr); first = sep_ptr + 1 ; // skip seperator while (*first == sep_char) { ++first; } } return head_ptr; } int main() { char test_case[] ="www.sina.com....cn"; size_t len = sizeof(test_case)/sizeof(test_case[0]); printf("before %s\n", test_case); // ignore '\0'; printf("after %s\n", string_word_reverse( test_case, test_case + len - 1, '.')); }