使用字符串流从字符串中删除空格的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”。

以下是将字符串输入中的空格删除以使其成为字符流的详细代码 -

Open Compiler
#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; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Aforapple,bforball

示例(使用getline)

我们还有另一种方法可以使用getline来解决C++中的相同问题。

Open Compiler
#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 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告