Re: sub string



I have in the variable  gchar *aux = "name_of_directory/name_of_file";
I want to copy only the substring /name_of_file to another gchar ...
how can i do that??
with strtok??

You can do it with strtok or what I use is rindex: 

strcpy( new_string, rindex( aux, '/' ));

is one way to do it.  This is pure C though, I don't know if there is a gtk*
way of doing it :)

rindex, what is that? I never heard of this and 
I can't find it on K&R or any of my C books...

You can do for example:

char *ptr;
ptr = strtok (aux, "/"); /* ptr now points to name_of_directory */
ptr = strtok (NULL, "/"); /* ptr now points to name_of_file */

1) Everytime you call strtok, it returns a pointer to
the next token contained between delimiters defined by
the second parameter. You don't need to allocate
memory for ptr, as it just points to somewhere in
aux space.

2) The NULL parameter in the second call tells strtok
to keep using the aux string to search (internally this
is done using a static variable). This way strtok continues
searching from the place where it stopped last time.

3) You can use as many delimiters as you want,
for example ptr = strtok (aux, "\n\t \/*_#,.");
or ptr = strtok (aux, string_containing_current_delimiters);

4) you can change delimiters from one call to
the next, even if the string remains the same.

5) strtok automatically ends each token with
a '\0', so you can handle the token using conventional
techniques. However, this also means that strtok
is a DESTRUCTIVE function. If you need the raw
aux string later on, you should save it before
it gets sliced by strtok (typically using strcpy).

6) when strtok reaches the end of aux, it returns NULL, naturally.

6) If you want to know more about advanced string
handling on C, you might wish to grab a copy of

"Advanced C Programming by example", John W. Perry,
PWS Publishing Company, Boston 1998.

Among other jewels it has a really good chapter 
on string handling (AINSI functions in depth, security, etc...).

Carlos




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]