C/C++練習(一)——將句子倒序輸出:輸入“how are you"倒序輸出"you are how"

//輸入“how are you"倒序輸出"you are how"

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str; //字符串
    int ptr[100];

    while (getline(cin, str))
    {
        int n = str.size();
        int count=0; //空格數量
        int b = n;
            
        //統計字符串中空格數量
        for (int i = 0; i < n; i++)
        {
            if (str[i] == ' ')
            {
                ptr[count] = i;
                cout << "ptr[count]:" << ptr[count] << endl;
                cout << "str[count]:" << str[ptr[count]-1] << endl;
                count++;
            }
        }
        cout << "count = " << count << endl;
        count--;
        //倒序輸出單詞
        for (int j = n ; j >= 0; j--)
        {
            if (j == ptr[count] && count >= 0)
            {
                for (int k =  ptr[count] + 1; k < n; k++)
                {
                    cout << str[k];
                }
                cout << " ";
                n = ptr[count];
                count--;
            }
        }
        
        for (int i = 0; i < ptr[0]; i++)
        {
            cout << str[i];
        }
        cout << endl;
    }
    return 0;
}


 

發佈了142 篇原創文章 · 獲贊 160 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章