Home > Software design >  Splitting text in C
Splitting text in C

Time:07-26

I am trying to make a LCD-Display showing the title and artist of a song, in order to connect it to my home media setup. I want to pass the information through via serial connection in the following layout:

title;artist

This could be for example:

Stitches;Shawn Mendes
GANGNAM STYLE(강남스타일) M/V;PSY

As you can see: Spaces and non-english characters can be common. How would I split this in two different variables(title and artist)?

Note that I am a beginner in C, using it on my arduino Uno to make little hobby projects.

CodePudding user response:

as your separator is in ascii part you may just loop until the char is ';'

each utf8 multibytes chars are always > 127, so you may not have any false positive

#include <stdio.h>

char string[] = "GANGNAM STYLE(čččč강남스타일) M/V;PSY" ;

int main(void){
    char *artist, *title = string, *p = string ;

    while( *p && *p != ';' ) p   ;
    
    if( !*p ) return 1 ; // ';' not found

    *p   = 0 ; // end of title string, overwrite the ';'
    
    artist = p ; // start of artist string
    
    printf( "title %s\nartist %s\n", title, artist ) ;
    
    return 0 ;
}

CodePudding user response:

Here's my function that mimics Python's split() method.

// Split string by a delimeter, results saved to linedata
void split_by_delim(char *src, char *delim, char **linedata, size_t size) 
{
    char *tok = strtok(src, delim);
    size_t sz = 0;

    while (tok != NULL && sz < size) {
        linedata[sz  ] = tok;     
        tok = strtok(NULL, delim);
    }
}

Usage:

char your_string[] = "GANGNAM STYLE(강남스타일) M/V;PSY";
char *data[2];
split_by_delim(your_string, ";", data, 2);

printf("Song: %s\n", data[0]);
printf("Artist: %s\n", data[1]);

Just field tested this with C11. But if you don't have access to standard library, you'll have to go with the @r043v's solution.

  •  Tags:  
  • c
  • Related