text 使用strtok()在标记中分隔一个字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text 使用strtok()在标记中分隔一个字符串相关的知识,希望对你有一定的参考价值。

Description

The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.

This function is part of <string.h>

Declaration
Following is the declaration for strtok() function.

char *strtok(char *str, const char *delim)
Parameters
str − The contents of this string are modified and broken into smaller strings (tokens).

delim − This is the C string containing the delimiters. These may vary from one call to another.

Return Value
This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve.

Example
The following example shows the usage of strtok() function.

#include <string.h>
#include <stdio.h>

int main () {
   char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";
   char *token;
   
   /* get the first token */
   token = strtok(str, s);
   
   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −

This is 
www.tutorialspoint.com 
website

Another example:

How we represent a music note:

A#4@1/8

In the code:

  // Parse line into note and duration
      string note = strtok(line, "@");
      string fraction = strtok(NULL, "@");
      
      
We also did the same thing when calculating the duration of the music note:

Like if the fraction we get is X/Y, we would parse this string into nominator and denominator of the fraction, and then we can calculate it.

// Parse length into d and e
    string d = strtok(length, "/");
    string e = strtok(NULL, "/");
    
So d is the top of the fraction, e is the bottom of the fraction. Then we can calculate.

以上是关于text 使用strtok()在标记中分隔一个字符串的主要内容,如果未能解决你的问题,请参考以下文章

strtok — 标记分割字符串

strtok — 标记分割字符串

使用strtok从字符串中解析空标记

strtok() 如何将字符串拆分为 C 中的标记?

提取并显示从 PHP 中的文本文件中分隔的所有 10 位数字逗号

如何更改字符串中分隔两种货币的逗号?