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;
}


 

发布了150 篇原创文章 · 获赞 200 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/qq_37764129/article/details/104387919