tags:

views:

404

answers:

7

Hi, I was wondering how you could take 1 string, split it into 2 with a delimiter, such as space, and assign the 2 parts to 2 separate strings. I've tried using strtok(); but to no avail.

Thanks!

Mr. Man

A: 

If you're open to changing the original string, you can simply replace the delimiter with \0. The original pointer will point to the first string and the pointer to the character after the delimiter will point to the second string. The good thing is you can use both pointers at the same time without allocating any new string buffers.

Mehrdad Afshari
A: 

If you have a char array allocated you can simply put a '\0' wherever you want. Then point a new char * pointer to the location just after the newly inserted '\0'.

This will destroy your original string though depending on where you put the '\0'

Brian R. Bondy
+6  A: 

I assume you're using C.

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);
ereOn
thank you!!!! this is exactly what i was looking for!!!
Mr. Man
`strtok()` modifies its input, so using it on a string literal is bad juju (a.k.a undefined behavior).
John Bode
Yep. I forgot to mention that. Thanks.
ereOn
@ereOn: Perhaps you missed the point. Your example is passing a pointer to a string literal, therefore strtok() will be modifying the string literal and invoking UB.
Fred Larson
My point was to demonstrate the basic use of strtok(). Well, I admit that using string literals in this situation is a bad pratice and should be avoided.Fun fact: if you look at http://www.cplusplus.com/reference/clibrary/cstring/strtok/ you can see the same "mistake" in the example.
ereOn
I think if you change `char *line = "SEVERAL WORDS"` to `char line[] = "SEVERAL WORDS"`, you're all set.
Fred Larson
If this is true, I just learned something. I thought those two instructions had the same meaning. My bad.
ereOn
@ereOn: Pointers and arrays are different things in C, until you sneeze near an array, and then it turns into a pointer. That's how the array size expression `sizeof(arr)/sizeof(arr[0])` works.
David Thornley
Ok ;) Thanks for the update.
ereOn
+1  A: 
char *line = strdup("user name"); // don't do char *line = "user name"; see Note

char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " ");   //sec_part points to "name"

Note: strtok modifies the string, so don't hand it a pointer to string literal.

N 1.1
A: 

You can use strtok() for that Example: it works for me

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

int main ()
{
 char str[] ="- This, a sample string.";
 char * pch;
 printf ("Splitting string \"%s\" into tokens:\n",str);
 pch = strtok (str," ,.-");
 while (pch != NULL)
 {
   printf ("%s\n",pch);
   pch = strtok (NULL, " ,.-");
 }
 return 0;

}

mkafkas
+1  A: 

For purposes such as this, I tend to use strtok_r() instead of strtok().

For example ...

int main (void) {
char str[128];
char *ptr;

strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);

printf ("'%s'  '%s'\n", str, ptr);
return 0;
}

This will output ...

'123456' '789asdf'

If more delimiters are needed, then loop.

Hope this helps.

Sparky
What's the difference betwen strtok_r() and strtok()?
thecoshman
strtok_r() is the reentrant version of strtok(). More about reentrancy here: http://en.wikipedia.org/wiki/Reentrant_%28subroutine%29
ereOn
A: 

You can do:

char str[] ="Stackoverflow Serverfault";
char piece1[20] = ""
    ,piece2[20] = "";
char * p;

p = strtok (str," "); // call the strtok with str as 1st arg for the 1st time.
if (p != NULL) // check if we got a token.
{
    strcpy(piece1,p); // save the token.
    p = strtok (NULL, " "); // subsequent call should have NULL as 1st arg.
    if (p != NULL) // check if we got a token.
        strcpy(piece2,p); // save the token.
}
printf("%s :: %s\n",piece1,piece2); // prints Stackoverflow :: Serverfault

If you expect more than one token its better to call the 2nd and subsequent calls to strtok in a while loop until the return value of strtok becomes NULL.

codaddict
Looks good, except the second strtok() call is using a different delimiter.
John Bode
@John: Thanks for pointing :)
codaddict