r3g_null1fy's blog

By r3g_null1fy, 12 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;




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

»
12 years ago, # |
  Vote: I like it +1 Vote: I do not like it
Very useful, thanks!
»
12 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

you forgot about strcmp and very much other funcs. i think the link to the official c++ site will be useful.

  • »
    »
    12 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    I don't think the site you pointed to is official.
    • »
      »
      »
      12 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it
      maybe not, but there are a lot of functions described with examples =)
»
12 years ago, # |
  Vote: I like it 0 Vote: I do not like it
"The book, Game of thrones is very good. Read it."

That is very true :)