how to split a string with string in c -
i have string
char *str = 1000000sep0002006sep736794eesep13610015741sep-1seplocal
i want split string "sep" , need ans like
string1 =1000000 string2 =0002006 string3 =736794ee string4 =13610015741 string5 =-1 string6 =local
thanks in advance
you can tokenise repeated calls strstr
. how simple function wrap , handle null safely:
char *next_token( char *str, const char *tok ) { if( str == null ) homecoming null; char *s = strstr(str, tok); if( s == null ) homecoming null; *s = 0; s += strlen(tok); homecoming s; }
then it's just:
char *string1 = str; char *string2 = next_token( string1, "sep"); char *string3 = next_token( string2, "sep"); // etc...
but i'd more inclined utilize array.
char * strings[6] = { str, 0 }; for( int = 1; < 6; i++ ) { strings[i] = next_token( strings[i-1], "sep" ); }
[edit]
as user unwind mentions in comments, cannot tokenise string literal this. if need operate on string literals, need tokenised extracts substrings without modifying original. that's exercise you. if want around it, create string char
array instead:
char str[] = "1000000sep0002006sep736794eesep13610015741sep-1seplocal";
you allowed modify that, because it's not pointer string literal. instead, it's array initialised re-create of string literal.
okay, i've said "string literal" plenty times now...
c string
No comments:
Post a Comment