首页 > 编程语言 >C++ 输入一句话,然后把这个字符串以单词为单位,逆转输出。(腾讯笔试题) 比如将“Alice call Jack”转换为“Jack call Alice”,

C++ 输入一句话,然后把这个字符串以单词为单位,逆转输出。(腾讯笔试题) 比如将“Alice call Jack”转换为“Jack call Alice”,

时间:2022-08-15 18:12:45浏览次数:56  
标签:int Alice C++ call Jack include

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main() {
    string str;
    int i = 0;  //访问字符数组的下标
    int count = 0;

    cout << "请输入一句话:" << endl;
    getline(cin, str);

    while (str[i]) {     //跳过前面的空格
        while (str[i] == ' ') i++;  //该循环结束后,str[i]是下一个单词的第一个字母
        int j = i;
        while (str[j] && str[j] != ' ') j++;  //该循环结束后,str[j]是这个单词后面的下一个位置
        //逆转这个单词
        for (int k1 = i, k2 = j - 1; k1 < k2; k1++, k2--) {
            char tmp = str[k1];
            str[k1] = str[k2];
            str[k2] = tmp;
        }
        i = j;
    }
    for (int k1 = 0, k2 = i - 1; k1 < k2; k1++, k2--) {
        char tmp = str[k1];
        str[k1] = str[k2];
        str[k2] = tmp;
    }
    cout << str << endl;
    system("pause");
    return 0;
}

 

标签:int,Alice,C++,call,Jack,include
From: https://www.cnblogs.com/smartlearn/p/16589212.html

相关文章