Anonymous Anonymous - 1 year ago 61
C++ Question

Check string for recurrence of specific character

How can I search inside of a string for more than one occurrence of a specific character (in this case a period


I have already tried adapting the answer from this question, but I think I am doing it wrong.

std::string periodCheck = i.convert_to<std::string>();
char subString = '.';
std::size_t pos = periodCheck.find(subString, 0);
int counter;
while(pos != std::string::npos){
if(counter > 1){
std::cout << "\nError: Multiple periods\n";
return false;

The first line simply converts from a Boost multiprecision arbitrary float to a string. I know that this part of the code works, because I am using it effectively elsewhere in the program. The variable
is the arbitrary float that I am converting to a string.

The rest of it is where I believe I am going wrong.

I am trying to check if a string contains more than one period. If the string has more than one period in it, I return false (this code is inside a function).

How can I achieve this?

Answer Source

If you find a period, then your next logical step would also be to search again, starting with the next character position.

However, if you review your code, you will not be able to find any place where it is actually searching again. There's no call to find() inside the while loop.

A while loop is not required at all. All you need to do is to call find() a second time, specifying pos+1 as the starting position for the second search, and check the results again. If you find another period, you can call it a wrap. Nothing is to be gained by searching for any remaining periods in the string. You have your answer.

std::size_t pos = periodCheck.find(subString, 0);

if (pos != std::string::npos)
     pos=periodCheck.find(subString, pos+1);
     if (pos != std::string::npos)
          return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download