C-language string segmentation, C-language string segmentation
It is very interesting to say that I think I have a deep understanding of the C language. But today, I only know that there is a strtok function. I tried it and suddenly felt how much repetitive work I had done before. Every time you need to parse the configuration file, and each time you need to split the string, you actually split the string by yourself, which is both tiring and error-prone. I'm not familiar with this technology! Here we reference A Piece Of strtok usage:
The strtok () function returns a pointer to the next "token" in str1, where str2 contains the delimiters that determine the token. strtok () returns NULL if no token is found. in order to convert a string to tokens, the first call to strtok () shocould have str1 point to the string to be tokenized. all callafter this shoshould have str1 be NULL.
For example:
Char str [] = "now # is the time for all # good men to come to the # aid of their country"; char delims [] = "#"; char * result = NULL; result = strtok (str, delims); while (result! = NULL) {printf ("result is \" % s \ "\ n", result); result = strtok (NULL, delims);}/* Ask hovertree.com */
- The above code will display the following output:
- Result is "now"
- Result is "is the time for all"
- Result is "good men to come to"
- Result is "aid of their country"
This function is similar to the lexical analysis in the compiler. It will solve many problems in future text processing. It seems necessary for me to systematically study C's library functions, not just syntax and algorithm skills. In this way, you can get twice the result with half the effort in your normal work.
Using this function, the configuration file shown below is very easy to parse:
id1 value1 value2 value3
id2 value1 value2 value3
...
Using this function makes it easier to split strings, for example, the following string to be split:
12|2345|asld|alsfalskd
You only need to read the data to be processed and call strtok four times to parse the values of each row. In the past, I used sscanf instead of parsing it myself, but strtok is more suitable and flexible!
Recommended:
Http://www.cnblogs.com/roucheng/p/3454292.html