-2

How can I replace each occurrence (in a string) of whitespace with an underscore?

I may only use the following standard headers:

  • <iostream>
  • <string>
  • <cctype>
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Musa
  • 21
  • 2
  • 1
    You didn't use the post preview. :( Have you considered searching for existing questions and research material on replacing characters with other characters in a string? – Lightness Races in Orbit Feb 10 '15 at 00:10
  • 1
    This would be an exact duplicate of http://stackoverflow.com/q/2896600/560648 if it weren't for what seems like an entirely arbitrary restriction on what headers you may use. Homework? Have you tried anything yet? – Lightness Races in Orbit Feb 10 '15 at 00:11
  • @LightnessRacesinOrbit Well, it's not quite the same. The linked question only replaces a single character, while this question asks about any sort of whitespace, which could include space, tab, newline, and maybe some more. – BWG Feb 10 '15 at 00:16
  • Is it one underscore per whitespace character, or per block of contiguous whitespace? – M.M Feb 10 '15 at 00:34

3 Answers3

1

The brute force method:

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] = '_';
  }
}

Only the header <string> is required.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
1

The obvious method seems to be:

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

Note a couple of points:

  1. You want to use isspace, not compare directly to the space character. If you do, you'll miss things like tabs.
  2. You want to cast the character to unsigned char before passing to isspace. Otherwise it can (and often will) have problems with characters outside the basic ASCII character set (e.g., letters with accents/umlauts).
T.C.
  • 133,968
  • 17
  • 288
  • 421
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

There's no single C++ string method to do this - you'll need a loop:

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

If you happened to have a null terminated C string, you could do this:

/* 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: generalized solution to use "isspace()": replaces all "whitespace" characters.

FoggyDay
  • 11,962
  • 4
  • 34
  • 48