输入一行字符串,把字符串翻转

输入一行字符串,把字符串翻转

/*输入一行字符串,把字符串翻转 。
Input: I____am__a__student
Output: student__a__am____I

(1)直接翻转一下
(2)把每个单词找出来,原地自身翻转
*/

#include 
#include 
#include "string.h"

void strReverse(char str[]) {
    int slen = strlen(str);
    for (int i = slen - 1; i >= 0; i--) {
        putchar(str[i]);
    }
    putchar('\n');
}

int main() {
    int i = 0, flag = 0, count = 0, wordlen = 0;
    char str[50];
    char word[50];
    int slen = 0;
    printf("请输入长度不超过50的字符串 !!\n");
    while (gets(str) != NULL) {
        slen = strlen(str);
        //逆序拣选单词,然后再将单词逆序输出。
        for (i = slen - 1, count = 0, flag = 0; i >= 0; i--) {
            if (flag == 0 && str[i] != ' ') { ////当前遇到新单词首
                count++;
                flag = 1;
                wordlen = 0;
                word[wordlen++] = str[i];

            } else if (flag == 1 && str[i] != ' ') { //把单词字符加入到数组中
                word[wordlen++] = str[i];
                word[wordlen] = '\0';
//                putchar(str[i]);
                flag = 1;
            } else if (flag == 1 && str[i] == ' ') {//当前遇到第一个空格
//                puts(word);
                strReverse(word);
                wordlen = 0;
//                putchar('\n');
                flag = 0;
            }
        }
//        puts(word);
        strReverse(word);
        printf("count is %d \n", count);
    }

}



你可能感兴趣的:(C)