0

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

例如:

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;
}

任何帮助表示赞赏!

4

5 回答 5

3

边界检查!

您忘记检查内部循环中的边界访问: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());
于 2013-04-21T17:38:46.220 回答
2

如果可以使用Boost,则可以执行以下操作:

#include<boost/algorithm/string.hpp>
...
erase_all(str, " ");

否则,我会建议这个替代方案:

#include<cctype>
#include<algorithm>
...
str.erase(std::remove (str.begin(), str.end(), ' '), str.end());
于 2013-04-21T17:40:02.757 回答
1

您可以使用久经考验的erase remove idiom ,而不是实现自己的解决方案:

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

int main()
{
  std::string s("a b c d e f g");
  std::cout << s << "\n";
  const char_to_remove = ' ';
  s.erase(std::remove(s.begin(), s.end(), char_to_remove), s.end() );
  std::cout << s << "\n";
}
于 2013-04-21T17:33:08.130 回答
1

您需要在处理后调整字符串大小。例如在末尾添加一行remove_space

str.resize(j);
于 2013-04-21T17:34:13.273 回答
1
#include<cctype>
#include<algorithm>

bool my_isspace(char c) {
    return std::isspace(c);
}

str.erase(remove_if(str.begin(), str.end(), my_isspace), str.end());

应该做的工作。


关于你的功能

void remove_spaces(string& str)
{
    int len = str.length();
    int j = 0, i = 0;

    while (j < len) 
    {
        if (str.at(i) == ' ') {
          ++j;
        }
        str.at(i) = str.at(j);
        ++i;
        ++j;
    }


    // You are missing this
    str.erase(i,len);
}
于 2013-04-21T17:31:54.873 回答