C++字串反轉

來源:互聯網
上載者:User

標籤:tle   輸入   amp   字串   string   c++   cto   輸出   字元   

如題,輸入一個字串,根據空格反轉單詞,

問題描述:

1、單詞構成:無空白字元構成一個單詞

2、輸入字串可以包含前置和尾隨空格,但反轉後的字元不能包括。

3、每個單詞之間存在多個空格

方法:先提取每個單詞,每次反轉。

代碼:

#include <string>

#include <vector>

 string reverseString1(string& str)
{
    std::string::size_type pos;
    std::string result;
    str += " "; //擴充字元串以方便操作,防止沒有尾隨空格
    int size = str.size();
    string ret;
    for (int i = 0; i < size; i++)
    {
        pos = str.find(‘ ‘, i);
        if (pos < size && pos != i)
        {
            std::string s = str.substr(i, pos - i);
            reverse(s.begin(), s.end());
            ret += s + " ";
            i = pos;
        }
    }
    ret.erase(--ret.end()); // 刪除最後多餘的空格
    return ret;
} 測試結果:輸入:

std::string test(" I have a little dog. ");
test = reverseString1(test);

輸出:test = "I evah a elttil .god"

C++字串反轉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.