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

标签 c++

我试图从字符串中删除空格,以尝试使用字符串本身,但它根本无法正常工作。在调试时,我发现它在字符串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++;
    }
}

最佳答案

str1[increment]对于任何increment > 0都是UB,因为str1的长度仅为1。您还将字符的值添加到每个元素,而不是附加字符串。只是改变

str1[increment] += str[i]
str1 += str[i]
并将string str1 = " ";更改为string str1;

关于c++ - 使用另一个字符串从字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62637727/

相关文章:

c++ - 预计算查找表和 "branch prediction"的设计模式

c++ - 加载共享库 : libSDL2_mixer-2. 0.so.0 时出现“错误:无法打开共享对象文件:没有这样的文件或目录

c++ - Qt 应用程序 : Failed to load platform plugin “windows”

c++ - 使用 c++ STL/Boost 而不是 system() 调用重写这个简单的函数?

python - 导入错误 dlopen () 符号未在平面命名空间中找到

c++ - 监控单个程序的 CPU 和磁盘利用率

c++ - Spritebatch 只绘制第一个 Sprite

C++:同一对象的基类与派生类的指针比较

c++ - linux c/c++编程支持设置进程优先级吗?

c++ - fatal error C1083 : Cannot open include file: 'boost/config.hpp' : No such file or directory