当分隔符是字符串时strtok()

时间:2016-01-08 11:27:11

标签: c strtok

当分隔符是字符串时,我想使用strtok() " break point "

This is the first part. break point This is the second part

成为:

  1. This is the first part.
  2. This is the second part
  3. 问题是当我包含空格时,它也会在每个空格中实现。

    以下是相关代码:

    char seps[5] = " $$$ ";
    char *token;
    char current[500] = {0};
    int i=0;
    while(fgets(current, 500, relevantFile) != NULL){
       printf("number %d:\n", i+1);
       token = strtok(current, seps);
       while(token != NULL){
          printf(token);
          printf("\n");
          token = strtok(NULL, seps);
       }
       printf("\n");
       i++;
    }
    
    当前为“Einstein, 1900 $$$ Mozart, 1700”时

    控制台中的预期答案是:

    number 1:
    Einstein, 1900
    
    number 2:
    Mozart, 1700
    

    但它会打印出来:

    number 1:
    Einstein,
    1900
    
    number 2:
    Mozart,
    1700
    

2 个答案:

答案 0 :(得分:1)

要删除子字符串,您可能想尝试使用strstr()。找到你想要删除的子字符串,然后在其中放置一个空终结符'\ 0'和strcat()到它后面的剩余部分。

例如:

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

void removeSubstr (char *string, char *sub) {
    char *match;
    int len = strlen(sub);
    while ((match = strstr(string, sub))) {
        *match = '\0';
        strcat(string, match+len);
    }
}

int main(int argc, const char *argv[]) {
    char test[] = "okay/op 1234 /opdone";
    removeSubstr(test, "/op");
    puts(test);
    return 0;
}

编辑: 代码中的seps字符串应为“$$$”而不是“$$$”。这将解决您的问题。

答案 1 :(得分:0)

该功能可以按照以下方式查看,如演示程序中所示

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

char * split_string( char *s, const char *delimiter )
{
    static char *p;

    if ( s ) p = s;

    size_t n = strlen( delimiter );

    if ( p && n != 0 )
    {
        while ( memcmp( p, delimiter, n ) == 0 ) p += n;
    }

    if ( !p || !*p ) return p = NULL;

    char *t = p;

    if ( n != 0 ) p = strstr( t, delimiter );

    if ( n == 0 || !p )
    {
        p = t + strlen( t );
    }
    else
    {
        *p = '\0';
        p += n;
    }

    return t;
}

int main( void )
{
    char s1[] = "This is the first part. break point This is the second part";
    char t1[] = " break point ";

    char *p = split_string( s1, t1 );

    while ( p )
    {
        puts( p );
        p = split_string( NULL, t1 );
    }
    char s2[] = "Einstein, 1900 $$$ Mozart, 1700";
    char t2[] = " $$$ ";

    p = split_string( s2, t2 );

    while ( p )
    {
        puts( p );
        p = split_string( NULL, t2 );
    }

    return 0;
}

程序输出

This is the first part.
This is the second part
Einstein, 1900
Mozart, 1700