在 C 中使用 strtok 使用多个分隔符拆分字符串 [英] Split string with multiple delimiters using strtok in C

查看:47
本文介绍了在 C 中使用 strtok 使用多个分隔符拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problem with splitting a string. The code below works, but only if between strings are ' ' (spaces). But I need to split strings even if there is any whitespace char. Is strtok() even necessary?

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," ");
  }

推荐答案

一个简单的示例,展示了如何在代码中使用多个分隔符和潜在的改进.请参阅嵌入的注释以获取解释.

A simple example that shows how to use multiple delimiters and potential improvements in your code. See embedded comments for explanation.

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

Be warned about the general shortcomings of strtok() (from manual):

这些函数修改它们的第一个参数.

These functions modify their first argument.

这些函数不能用于常量字符串.

These functions cannot be used on constant strings.

分隔字节的标识丢失.

strtok() 函数在解析时使用静态缓冲区,所以它不是线程安全的.如果这对您很重要,请使用 strtok_r().

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 中使用 strtok 使用多个分隔符拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆