r3g_null1fy's blog

By r3g_null1fy, 13 years ago, In English
Here are the some of the  lesser know string.h functions


strtok
This is the most useful functions. It is used to split a string based on some pattern string.
char * strtok ( char * str, const char * delimiters );

char *word;

char s[] = "The book, Game of thrones is very good. Read it.";
char delim[] = " ,.";   //if you want to split on dot, space and comma.

for (word = strtok(s, delim); word; word = strtok(0, delim))
       cout << word<<endl;

This prints
The 
book
Game
of 
thrones 
is
very
good
Read 
it


size_t strspn ( const char * str1, const char * str2 );

Get span of character set in string

Returns the length of the initial portion of str1 which consists only of characters that are part of str2.

For example, if we wanted to test if a number was lucky(i.e only consisting of digits 4 and 7) we could write 
if (strspn(s,"47") == strlen(s)) 

We can now write the codeforces 104 div 2 problem a solution like this
if (strspn(s,"47") == strlen(s) &&
             accumulate(s,s+strlen(s)/2,0) ==  accumulate(s+strlen(s)/2,strlen(s),0) 
      cout <<"YES";
else 
   cout<<"NO";


size_t strcspn ( const char * str1, const char * str2 );

Get span until character in string

Scans str1 for the first occurrence of any of the characters that are part of str2, returning the number of characters of str1 read before this first occurrence


strpbrk
const char * strpbrk ( const char * str1, const char * str2 );
      char * strpbrk (       char * str1, const char * str2 );

Locate character in string

Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.

in codeforces beta round 96 div 2 problem a, we have to print "YES" if the input consists of any of these characters 'H','Q' or '9'
this can be easily done using strpbrk

cout << (strpbrk(s,"HQ9") != NULL ? "YES" : "NO") << endl;




Full text and comments »

  • Vote: I like it
  • +48
  • Vote: I do not like it