0

i have a string

char *str = 1000000sep0002006sep736794eesep13610015741sep-1seplocal

i want to split the string with "sep" and i need the ans like

String1 =1000000
String2 =0002006
String3 =736794ee
String4 =13610015741
String5 =-1
String6 =local

Thanks in advance

4
  • 2
    Ironically, you can use strsep. Or strtok. These are in string.h. Commented Feb 18, 2013 at 8:03
  • 1
    @squiguy Only if dealing with single-character delimiters. Commented Feb 18, 2013 at 8:10
  • 1
    Note that strsep() is not a standard function (not in POSIX or C), but it may be quite widely available even so. It deals in single character delimiters, so it probably isn't appropriate here where you seem to have a 3-character delimiter. Also, arrays in C are indexed from 0 — you did mean to use an array, didn't you? Commented Feb 18, 2013 at 8:11
  • have tried with strtok(). but using that function we can split it using single character. Commented Feb 18, 2013 at 11:14

1 Answer 1

4

You can tokenise it yourself by repeated calls to strstr. How about a simple function to wrap it up and handle NULL safely:

char *next_token( char *str, const char *tok )
{
    if( str == NULL ) return NULL;
    char *s = strstr(str, tok);
    if( s == NULL ) return NULL;
    *s = 0;
    s += strlen(tok);
    return s;
}

Then it's just:

char *string1 = str;
char *string2 = next_token( string1, "sep");
char *string3 = next_token( string2, "sep");
// etc...

But I'd be more inclined to use an array.

char * strings[6] = { str, 0 };
for( int i = 1; i < 6; i++ ) {
    strings[i] = next_token( strings[i-1], "sep" );
}

[edit]

As the user unwind mentions in comments, you cannot tokenise a string literal like this. If you need to operate on string literals, then you need a tokenised that extracts substrings without modifying the original. That's an exercise for you. But if you want to get around it, just make your string a char array instead:

char str[] = "1000000sep0002006sep736794eesep13610015741sep-1seplocal";

You are allowed to modify that, because it's not a pointer to a string literal. Instead, it's an array that is initialised with a copy of a string literal.

Okay, I've said "string literal" enough times now...

Sign up to request clarification or add additional context in comments.

2 Comments

Note though that since this modifies the input string, you can't use it on the exact code in the question, since str points at a character literal and thus is read-only.
Thanks @unwind you're quite right. I took the poster's 'code' as more of pseudocode for the general idea. But I will edit my answer to be explicit about string literals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.