如何使用c ++用下划线替换字符串中出现的空格?

时间:2015-02-10 00:08:33

标签: c++

如何用下划线替换每个空格(在字符串中)?

我只能使用以下标准标题:

  • <iostream>
  • <string>
  • <cctype>

3 个答案:

答案 0 :(得分:1)

显而易见的方法似乎是:

for (size_t i=0; i<s.size(); i++) 
    if (isspace((unsigned char)s[i])) 
        s[i] = '_';

请注意几点:

  1. 您想使用isspace,而不是直接与空格字符进行比较。如果你这样做,你就会错过像标签这样的东西。
  2. 您希望在传递给unsigned char之前将角色投射到isspace。否则它可能(并且经常会)出现基本ASCII字符集之外的字符问题(例如带有重音符号/变音符号的字母)。

答案 1 :(得分:0)

没有单一的C ++字符串方法可以做到这一点 - 你需要一个循环:

// C++ replace all
#include <cctype.h>
...
string string replaceChar(string str, char new_char) {
  for (int i = 0; i < str.length(); ++i) {
    if (isspace((unsigned char)str[i]))
      str[i] = new_char;
  }
  return str;
}

如果你碰巧有一个空终止的C字符串,你可以这样做:

/* C replace all */
#include <ctype.h>
...
char *replaceChar (char *str, char new_char) {
    char *p = str;
    unsigned char c;
    while (c = *p) {
      if (isspace(c))
        *p = new_char;
      p++;
    }
    return str;
}

ADDENDUM:使用&#34; isspace()&#34;的通用解决方案:替换所有&#34;空白&#34;字符。

答案 2 :(得分:0)

蛮力方法:

std::string text = "Is the economy getting worse?";
const unsigned int length = text.length();
for (unsigned int i = 0; i < length; ++i)
{
  if (text[i] == ' ')
  {
    text[i] = '_';
  }
}

只需要标题<string>