-
std::insert
I have a string, Five. I wonder if it is possible to insert a blancspace " "
so the string will look like this instead:
"Hello 5Hello"
When I use the code, the application get stuck so I have to force to end the program with the taskmanager.
Code:
std::string BigLine = "Hello5Hello";
std::string Five= "5";
std::string::size_type pos;
while(std::string::npos != (pos = BigLine.find(Five)))
{
BigLine.insert(pos, " ");
}
-
Perhaps because you have an infinite loop?
Maybe 'if' rather than 'while' ?
-
Yes, if did work but the problem will be when the string will look like this.
"Hello5Hello5Hello"
Then only the first occurence of 5 will be found and " " will be inserted before and next 5 will not.
Perheps the infinite loop is because the string grows.
I am not sure what I could do here.
-
You need to use the second parameter of find, which is the place to start looking.
Initialize pos to 0, then use BigLine.find(Five, pos). You might have to increment pos inside the loop because you're adding a character and you don't want it to find the same five again.
-
Thanks.. that make sense. I have put the code like this and increasing pos with one inside the loop. I beleive pos in the find( , pos) get this new value ?
However the loop seems to be infinite. Should I Initialize pos to 0 somewhere, I am not sure what effect that has then.
Code:
std::string BigLine = "Hello5Hello5Hello";
std::string Five= "5";
std::string::size_type pos;
while(std::string::npos != (pos = BigLine.find(Five, pos)))
{
BigLine.insert(pos, " ");
pos = pos + 1;
}
-
I think you should increase pos by two. If you weren't inserting a character and you didn't increase it at all, then it would keep finding the same 5 over and over (because it would start looking at the same spot where it found the previous one). So increase pos by one to account for that, then increase it by another one to account for the space you inserted.
-
yes I just found it out also. This worked great.
Thank you !
-
You should still initialize it to 0 at the definition.