c - 在 C 中使用 strtok 拆分具有多个定界符的字符串

标签 c string split

我在拆分字符串时遇到问题。下面的代码有效,但前提是字符串之间是 ' '(空格)。但即使有任何 whitespace 字符,我也需要拆分字符串。 strtok() 有必要吗?

char input[1024];
char *string[3];           
int i=0;

fgets(input,1024,stdin)!='\0')               //get input
{                                        
  string[0]=strtok(input," ");               //parce first string
  while(string[i]!=NULL)                     //parce others
  {
     printf("string [%d]=%s\n",i,string[i]);
     i++;
     string[i]=strtok(NULL," ");
  }

最佳答案

一个简单的示例,展示了如何使用多个定界符以及代码中的潜在改进。请参阅嵌入的评论以获取解释。

注意 strtok() 的一般缺点(来自手册):

These functions modify their first argument.

These functions cannot be used on constant strings.

The identity of the delimiting byte is lost.

The strtok() function uses a static buffer while parsing, so it's not thread safe. Use strtok_r() if this matters to you.


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

int main(void)
{    
  char input[1024];
  char *string[256];            // 1) 3 is dangerously small,256 can hold a while;-) 
                                // You may want to dynamically allocate the pointers
                                // in a general, robust case. 
  char delimit[]=" \t\r\n\v\f"; // 2) POSIX whitespace characters
  int i = 0, j = 0;

  if(fgets(input, sizeof input, stdin)) // 3) fgets() returns NULL on error.
                                        // 4) Better practice to use sizeof 
                                        //    input rather hard-coding size 
  {                                        
    string[i]=strtok(input,delimit);    // 5) Make use of i to be explicit 
    while(string[i]!=NULL)                    
    {
      printf("string [%d]=%s\n",i,string[i]);
      i++;
      string[i]=strtok(NULL,delimit);
    }

    for (j=0;j<i;j++)
    printf("%s", string[i]);
  }

  return 0;
}

关于c - 在 C 中使用 strtok 拆分具有多个定界符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26597977/

相关文章:

c - 使用 UTF-16 编码从管道读取 PowerShell 输出

Java EE、实体 Bean 和长字符串属性(mysql 文本)。如何?

c - 构造变量后使其成为常量

c - 如何在 C 中打印全零?

c - 在 C 中反转字符串

python - 在 pandas 中分割时间戳日期

java - java中如何根据条件分割字符串

c - 根据分隔符将单词附加到数组

c - 在汇编中写一个 fopen 函数

jQuery:将每个第 n 个单词包装在一个范围内