Tedfoo
Tedfoo

Reputation: 173

How do I separate strings based on multiple delimiters in C?

I have input of the form (first_string*second_string) where * can be one of three characters, x, y or z. I need to extract first_string and second_string as strings of their own.

I'm able to do this with strchr if * was always the same, but I'm not sure how to do this when * is one of three possible characters.

I'm assuming I need to use a function of the form

int star(char g) {
    if (g == 'x' || g == 'y' || g == 'z') {
        return 1;
    }
    else {
        return 0;
    }
}

but I'm not sure how to proceed from here. Can anyone help me out?

Upvotes: 3

Views: 675

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

There are many ways to do the task. For example you can use standard C function strtok declared in header <string.h>.

For example

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

int main( void )
{
    char s[] = "first_stringxsecond_string";

    const char *delimiters = "xyz";

    char *p = strtok( s, delimiters );

    while ( p )
    {
        puts( p );
        p = strtok( NULL, delimiters );
    }
}    

The program output is

first_string
second_string

Take into account that function strtok changes the original string by inserting the terminating zero. So you may not apply the function for string literals.

When you may not change the original string you should consider other approaches.

Upvotes: 3

rootkea
rootkea

Reputation: 1484

Given your star() function definition

char *ptr;
if(star(g))
{
    ptr = strchr(s, g);

    if(ptr)
        *ptr = '\0';  
    printf("First string = %s\n", s);

    if(ptr)
        printf("Second string = %s\n", ptr + 1);
}   

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Use strpbrk() instead of strchr().

Example

char *found;
if ((found = strpbrk(source, "xyz")) != NULL)
{
    // `found' now points to one of `x' or `y' or `z' in `source'
}

an obvious flaw is if the "strings" contain these characters.

Upvotes: 4

Related Questions