1

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){
    counter++;
    if(counter > 1){
        std::cout << "\nError: Multiple periods\n";
        return false;
    }
}

The first line simply converts from a Boost multi-precision cpp_dec_float (named i) to a string. I know that this part of the code works, because I use it effectively elsewhere in the program.

I am trying to check if a string contains more than one period. If the string has more than one period in it, the function returns false.

How can I achieve this?

Community
  • 1
  • 1
esote
  • 831
  • 12
  • 25

1 Answers1

3

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;
}
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148