-2

I know how to parse a string based on a delimiter, such as a comma. Does this require turning the string into an array of char?

I am wanting to compare a string that is 6 numebrs i.e. 111222

with another string of numbers that is 12 characters long but I only want the first six.

Basically way to check that 111222 occurs in the string 111222345678.

WorthAShot
  • 81
  • 1
  • 5
  • 1
    Keep in mind that checking the first few characters of a string and checking whether a string is contained in another string are two different problems. Other than that you should be able to use google – carloabelli Feb 08 '15 at 18:40

2 Answers2

2

....but I only want the first six

For first n chars comparison you can use std::strncmp

char s1[] ="111222345678" ;
char s2[] ="111222";

std::cout << std::strncmp( s1,s2, 6 ) ; // n =6 chars
P0W
  • 42,046
  • 8
  • 62
  • 107
  • Oh my goodness, it never occurred to just compare the string as a whole instead of cutting off the last 6 chars of the 12 number string. Thank you very much. – WorthAShot Feb 08 '15 at 18:53
2

using std::string, you could do

std::string sample = "111222345678";

if (sample.substr(0, 6) == "111222")
{
   ... do stuff here if ... 
}

Of course, this can be made more generic by having the string to match as a std::string too:

std::string match = "111222";
if (sample.substr(0, match.length()) == match))
{
  ... 
}
Mats Petersson
  • 119,687
  • 13
  • 121
  • 204
  • 1
    Maybe not quite as simple, but I'd use something like `if ( sample.size() >= match.size() && std::equal( match.begin(), match.end(), sample.begin() )`. – James Kanze Feb 08 '15 at 19:18