c++ - 使用带有指针参数的函数从字符数组中删除空格

标签 c++ arrays char spaces

所以我正在研究这本书,我遇到了一个练习,它(简要地)要求我使用函数删除字符数组的所有空格:void removeSpaces(char* s)

[包含iostream、cstring并定义SIZE]

这是 main():

int main() {
  char a[SIZE] = "a bb ccc d";
  cout << a << endl; // a bb ccc d
  removeSpaces(a);
  cout << a << endl; // a bb ccc d instead of abbcccd
}

这是 removeSpaces():

void removeSpace(char* s) {
  int size = strlen(s);

  char* cpy = s;  // an alias to iterate through s without moving s
  char* temp = new char[size]; // this one produces the desired string
  s = temp; // s points to the beginning of the desired string

  while(*cpy) {
      if(*cpy == ' ')
          cpy++;
      else
          *temp++ = *cpy++;
  }

  cout << s << endl; // This prints out the desired result: abbcccd
}

(我选择的名称并不理想,但现在别介意了。)所以我的函数基本上做了我想要它做的事情,除了结果在函数范围之外没有影响。我怎样才能做到这一点?我错过了什么,我做错了什么?

最佳答案

由于您按值传递指针,因此您肯定会就地更改数组。显然,您会像这样删除空格:

void removeSpaces(char* s) {
    *std::remove(s, s + strlen(s), ' ') = 0;
}

关于c++ - 使用带有指针参数的函数从字符数组中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27710117/

相关文章:

c# - 如何在 C# 中模拟/继承数组初始化语法?

c - 为什么我不能重用 c = getchar();在 str1 上使用后在 str2 上? (C)

c++ - 如何在批处理模式下工作

c++ - 加载两个具有相同符号的共享库时是否存在符号冲突

c++ - 如果 nullptr_t 不是关键字,为什么是 char16_t 和 char32_t?

c++ - 遇到值时中断

jquery - 从 jquery 数组加载 css 背景图像

javascript - 如何在 array.map() 中返回动态对象键

C 打印一个没有值(value)的字符

c - 从 C 中的字符串中删除指定的字符