Блог пользователя r3g_null1fy

Автор r3g_null1fy, 13 лет назад, По-английски
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;




  • Проголосовать: нравится
  • +48
  • Проголосовать: не нравится

»
13 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится
Very useful, thanks!
»
13 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится
What about complexity of strpbrk? O(lengthstr1·lengthstr2) ?
  • »
    »
    13 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    The C standard says nothing about the time/space complexity of the function (just as for most, if not all, standard library functions).
»
13 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

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

»
13 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится
"The book, Game of thrones is very good. Read it."

That is very true :)