使用字串流從字串中刪除空格的C++程式


正如題目所述,我們需要使用字串流從字串中刪除空格。顧名思義,字串流將字串轉換為流。它的工作方式類似於C++中的cin。它關聯一個字串物件,該物件可以訪問儲存它的字串緩衝區。

string s =" a for apple, b for ball";
res = solve(s);

使用字串緩衝區,我們將逐個讀取每個單詞,然後將其連線到一個新字串中,該字串將作為我們的答案。

注意 - stringstream類在c++的sstream標頭檔案中可用,因此我們需要包含它。

讓我們來看一些輸入/輸出場景

假設函式接收的輸入中沒有空格,則獲得的輸出結果與輸入相同 -

Input: “Tutorialspoint”
Result: “Tutorialspoint”

假設函式接收的輸入中沒有空格,則獲得的輸出結果將是去除所有空格的字串 -

Input: “Tutorials Point”
Result: “TutorialsPoint”

假設函式接收的輸入中只有空格,則該方法無法提供輸出結果 -

Input: “ ”
Result: 

演算法

  • 考慮一個包含字元的輸入字串。

  • 檢查字串是否不為空,並使用stringstream關鍵字刪除輸入中存在的所有空格。

  • 此過程一直持續到stringstream指標到達行尾。

  • 如果它到達字串的行尾,程式將終止。

  • 更新後的字串將返回到輸出結果。

示例

例如,我們有一個字串,例如“a for apple, b for a ball”,我們需要將其轉換為“aforapple,bforball”。

以下是將字串輸入中的空格刪除以使其成為字元流的詳細程式碼 -

#include <iostream> #include <sstream> using namespace std; string solve(string s) { string answer = "", temp; stringstream ss; ss << s; while(!ss.eof()) { ss >> temp; answer+=temp; } return answer; } int main() { string s ="a for apple, b for ball"; cout << solve(s); return 0; }

輸出

Aforapple,bforball

示例(使用getline)

我們還有另一種方法可以使用getline來解決C++中的相同問題。

#include <iostream> #include <sstream> using namespace std; string solve(string s) { stringstream ss(s); string temp; s = ""; while (getline(ss, temp, ' ')) { s = s + temp; } return s; } int main() { string s ="a for apple, b for ball"; cout << solve(s); return 0; }

輸出

Aforapple,bforball

結論

我們看到,使用字串流,字串儲存在緩衝區中,我們可以逐字獲取字串並將其連線起來,從而刪除空格。

更新於:2022年8月10日

802 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.