Check first two characters in string

Hi all, I would like to know how to check if the first two characters in a string are equal to a value.e.g I have a string containing 701285463257.

if(first two characters are 70){int o=2;}
else{o=3;}

Thanks :D
1
2
3
4
5
6
7
8
9
10
11
std::string someString("701285463257");

if ( (someString[0] == '7') &&
      (someString[1] == '0'))
{
  o = 3;
}
else
{
  o = 2;
}
I would add a guard using 2 <= someString.length(), as operator[] doesn't like being used on empty strings.
Last edited on
Alternatively, someString.substr(2)=="70", although it's a little more expensive.
Thanks so much guys :D
Another approach I sometimes use is 0 == someString.find("70")
Topic archived. No new replies allowed.