題目如下:
給定一個字串str,將字串中的單詞位置進行反轉,輸出反轉結果,
輸入:“student. a am I”,
輸出:“I am a student.”
解題思路如下:
遍歷字串,逐個字符進行判斷,如果不是空格的話,用tmp暫時保存,如果是空格的話,那么執行res = " "+tmp+res 進行反轉,然后將tmp重置為空串
代碼及注釋如下:
#include<iostream>
#include<string>
using namespace std;
string ReverseSentence(string str)
{
string res = "", tmp = "";//均初始化為空串
for (unsigned int i = 0; i < str.size(); ++i)//遍歷字串
{
if (str[i] == ' ')//遇到空格,進行反轉
{
res = " " + tmp + res;//反轉
tmp = "";//tmp重置為空串
}
else//不是空格,就保存在tmp中
{
tmp += str[i];
}
}
if (tmp.size())//如果最后一部分還有單詞但是沒有遇到空格了
res = tmp + res;//把最后一部分單詞加到字串的前面
return res;
}
int main()
{
string arr="student. a am I";
cout<<ReverseSentence(arr)<<endl;
return 0;
}
運行截圖如下:

代碼演示圖如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/258832.html
標籤:其他
上一篇:雙系統Windows10和Ubuntu18.04,開機或重啟遇到了grub黑屏怎么辦
下一篇:玩轉指標重難點(3)
