Why is string.find_first_of returning 1 every time?

I posted the whole function although the problem seems to be with the while statement. The problem is, string s is "dog?" and vector vs is {", ', ,, ., !, ?}, so presumably when i equals 5 and st equals 3, the erase should take place and s should be "dog", however st just equals 1 every time and the erase happens over and over until I'm left with just the first letter "d". Any help with this would be appreciated, thanks.

1
2
3
4
5
6
7
8
9
10
11
12
void removeCharacters(string &s, vector<string> vs)
{
	string::size_type st = 0;
	for (unsigned int i = 0 ; i < vs.size() ; i++)
	{
		while (st = s.find_first_of(vs[i], st) != string::npos)
		{
			s.erase(st, 1);
		}
	}
	return;
}
You need reset st to 0 in each iteration of the for loop.

You also need parenthesis around the assignment in the while condition.

When you pass a string to find_first_of it will search for first character that is equal to one of characters in the string you passed to the function, so if you store all characters of vs in a string you wouldn't need to use the for loop.
It's a vector of strings though, I don't think it'd work. Or would it?

Anyway, it's working now, so thanks for the help.
Yeah, I was just thinking that if you don't use vs for anything else that requires it to be a vector you could simplify the code if you made it a string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

void removeCharacters(string &s, string vs)
{
	string::size_type st = 0;
	while ((st = s.find_first_of(vs, st)) != string::npos)
	{
		s.erase(st, 1);
	}
}

int main()
{
	string vs = "\"',.!?";
	string s = "dog?";
	removeCharacters(s, vs);
	std::cout << s << std::endl;
}
Topic archived. No new replies allowed.