string - replace all NON alpha numeric with " " spaces

I have a near identical function with erase which works fine - the erase one simply erases all nonalnum including spaces.

Self explanatory what I want this function to do. For some reason it never enters the isalnum test whereas the erase one does.

Really confused...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
std::string ReplaceAllNonAlphaNumericWithSpace(std::string in)
{
	std::string out = "";

	size_t i = 0;
	size_t len = in.length();
	while (i < len){
		if (in[i] > 32 && in[i] < 255){
			if (!isalnum(in[i])){
				in.replace(i, 1, " ");
				len--;
			}
			else{
				i++;
			}
		}
		else
		{
			if (in[i] != ' ')
			{
				in.replace(i, 1, " ");
				len--;
			}
		}
	}

	out = in;
	return out;
}
Last edited on
You know you can assign to strings like they are arrays, right? No reason to call .replace for single characters.

Have you considered what happens if your loop starts on line 18? There seems to be no way to increment [tt]i[/ii] in that case. Why are you not simply using a for loop?
Ok. I changed it to a loop as you suggested and it seems to work now, thanks LB.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	std::stringstream ssOut;

	for (int i = 0; i < (int)in.length(); i++)
	{
		if ((in[i] >= '0' && in[i] <= '9')
			|| (in[i] >= 'A' && in[i] <= 'z'
			|| (in[i] == ' ')))
		{
			//skip character
		}
		else
		{
			in[i] = ' ';
		}

		ssOut << in[i];
	}
That still looks quite complex.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
#include <iostream>

std::string foo( std::string in ) {
    for ( auto & c : in ) {
        if ( ! isalnum( c ) ) c = 'X';
    }
    return in;
}

int main() {
    std::string word = "Hello, Dolly!";
    word = foo( word );
    std::cout << word << '\n';
    return 0;
}













HelloXXDollyX

It does not really matter that spaces gets replaced (with spaces).
Topic archived. No new replies allowed.