21xrx.com
2025-03-28 04:16:02 Friday
文章检索 我的文章 写文章
如何在 C++ 中去掉字符串中的空格
2023-07-04 21:09:20 深夜i     21     0
C++ 字符串 空格 去除 操作

在 C++ 中,去掉字符串中的空格是一个常见的应用需求。空格是指空格符、制表符、换行符等没有实际字符的符号。空格在字符串中有时会影响程序的运行结果和用户的感受,因此需要去掉它们。

下面介绍几种方法:

方法一:遍历字符串

遍历字符串,逐个判断每一个字符是否为空格,如果是空格则跳过,否则将其加入到新的字符串中。

#include <iostream>
#include <string>
using namespace std;
string removeSpace(string s) {
  string res = "";
  for (int i = 0; i < s.size(); i++) {
    if (s[i] != ' ' && s[i] != '\t' && s[i] != '\n') {
      res += s[i];
    }
  }
  return res;
}
int main() {
  string s = " hello world \t";
  string res = removeSpace(s);
  cout << "原字符串:" << s << endl;
  cout << "去掉空格后的字符串:" << res << endl;
  return 0;
}

方法二:使用库函数

C++ 中的库函数提供了丰富的字符串处理函数,我们可以使用 std::remove_if 函数和 std::isspace 函数来实现去掉字符串中的空格。

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
string removeSpace(string s) {
  s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
  return s;
}
int main() {
  string s = " hello world \t";
  string res = removeSpace(s);
  cout << "原字符串:" << s << endl;
  cout << "去掉空格后的字符串:" << res << endl;
  return 0;
}

方法三:使用正则表达式

C++11 提供了正则表达式库,我们可以使用 std::regex_replace 函数来实现去掉字符串中的空格。

#include <iostream>
#include <string>
#include <regex>
using namespace std;
string removeSpace(string s) {
  regex pattern("\\s+");
  return regex_replace(s, pattern, "");
}
int main() {
  string s = " hello world \t";
  string res = removeSpace(s);
  cout << "原字符串:" << s << endl;
  cout << "去掉空格后的字符串:" << res << endl;
  return 0;
}

无论采用哪种方法,都可以去掉字符串中的空格。在实际应用中,还需要考虑对原字符串的修改和返回值的处理等问题。

  
  

评论区

请求出错了