Check for symbols

I need a function to check if the inputted string contains a colon. It has to be in an if loop as the condition.
If you mean a character array then you can use standard C function strchr. For example

if ( const char *p = strchr( s, ':' ) ) std::cout << "The colon is in position " << p - s << std::endl;

You can write the function yourself. For example

1
2
3
4
5
6
const char * strchr( const char *s, char c )
{
   while ( *s != c && *s ) ++s;

   return ( *s == c ? s : 0 );
}


If you mean standard class std:;string then you can use its method find. For example

1
2
std::string::size_type n = s.find( c );
if ( n != std::string::npos ) std::cout << "The colon is in position " << n << std::endl;


Or you can write the similar logic yourself

1
2
3
4
5
std:;string::size_type n = 0;

for ( ; n < s.length() && s[n] != c; n++ );

if ( n != s.length() ) std::cout << "The colon is in position " << n << std::endl;
Topic archived. No new replies allowed.