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>
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>
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.
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:
isspace
, not compare directly to the space character. If you do, you'll miss things like tabs.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).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.