Reverse every word in a string (should handle space)

前端 未结 5 513
陌清茗
陌清茗 2020-12-11 12:16

Examples:

char test1[] = \"               \";
char test2[] = \"   hello  z\";
char test3[] = \"hello world   \";
char test4[] = \"x y z \";

5条回答
  •  醉梦人生
    2020-12-11 13:01

    In-place, ANSI C89.

    #include 
    #include 
    
    void reverse(char *s) {
        int i = 0, j, k;
        while (1) {
            while (isspace(s[i])) i++;
            if (!s[i]) return;
            for (j = i; !isspace(s[j]) && s[j] != '\0'; j++);
            for (k = 0; k < (j - i) / 2; k++) {
                char t = s[i + k];
                s[i + k] = s[j - k - 1];
                s[j - k - 1] = t;
            }
            i = j;
        }
    }
    
    int main(int argc, char**argv) {
        if (argc != 2) return 1;
        reverse(argv[1]);
        printf("%s\n", argv[1]);
        return 0;
    }
    

提交回复
热议问题