c++ - 从字符串中删除空格

标签 c++ string spaces

<分区>

我尝试编写一个函数来获取带空格的字符串并返回不带空格的字符串。

例如:

str = "   a  f  ";

将替换为“af”;

我的函数不起作用,它将字符串替换为:“af f”。

这是我的功能:

void remove_space(string& str) {
    int len = str.length();
    int j = 0, i = 0;
    while (i < len) {
        while (str.at(i) == ' ') i++;
        str.at(j) = str.at(i);
        i++;
        j++;
    }
}

int main ()
{
string str;
    getline(cin, str);
    remove_space(str);
    cout << str << endl;
return 0;
}

感谢任何帮助!

最佳答案

边界检查!

您忘记检查内部循环中的边界访问:while (str.at(i) == ' ') i++;

我重写了代码:

void remove_space(string& str)
{
    int len = str.length();
    int j = 0;

    for (int i = 0; i < len;)
    {
        if (str.at(i) == ' ')
        {
            i++;
            continue;
        }

        str.at(j++) = str.at(i++);
    }
    str.resize(j);
}

此外,您可以使用以下代码删除空格(建议在 cppreference.com 中):

str.erase(std::remove(str.begin(), str.end(), ' '), str.end());

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

相关文章:

C++ 字符串下标超出范围

c - 如何在 C 中读取其中包含空格的字符串?

html - CTRL + A 后菜单中的空格

bash - 使用具有各种引号级别和空格的变量构建命令字符串

c++ - 是否可以在实现文件中使用命名空间或等效项来避免在每个函数前加上类名?

c++ - 事件队列是否与用于跨线程信号/槽(在 Qt 中)的队列相同?

python - 用字符串替换 'match' 对象,Python

r - 在 R : remove commas from a field AND have the modified field remain part of the dataframe

c++ - 在 map 中已知值时获取键的最佳方法

C++和跳出动态生成代码的安全方式