提问者:小点点

使用另一个字符串从字符串中删除空格


我试图从字符串中删除空格,试图使用字符串本身,但它根本不起作用。 在调试时,我发现它在字符串str1中放入了奇怪的值,我不明白它为什么要这样做。 下面是附上的代码,有什么问题吗? 为什么不起作用?

string str = "Hello World";
string str1 = " ";
int increment = 0;

for (int i = 0; i < str.length(); i++) {
    if (str[i] == ' ') {
        continue;
    }
    else {
        str1[increment] += str[i];
        increment++;
    }
}

共3个答案

匿名用户

str1[increment]是任何增量>UB; 0,因为str1的长度只有1。 您还将一个字符的值添加到每个元素中,而不是附加一个字符串。 只要改变

str1[increment] += str[i]

str1 += str[i]

并将string str1=“”;更改为string str1;

匿名用户

而不是写循环,使用STL算法函数执行擦除。

首先,如果给定适当的参数,算法函数不会失败。

第二,代码本身基本上是自我文档化的。

例如,如果有人查看您的手工编码循环,乍一看并不清楚您想要完成的是什么。 另一方面,当C++程序员看到std::remove时,它会立即知道它会做什么。

将使用的STL alogrithm函数是std::remove,同时使用std::string::erase():

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string str = "Hello World";
    str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
    std::cout << str;
}

输出:

HelloWorld

匿名用户

它是Python中的代码:

txt = "hello world" spaces = " "

txt = txt.replace(" ", "")


print(txt)

您可以将其更改为任何您想要的语言。 它从句子中删除空格。