Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string in C without using strtok

Tags:

c

string

token

#include <stdio.h>
int
main() {
    char string[] = "my name is geany";
    int length = sizeof(string)/sizeof(char);
    printf("%i", length);
    int i;
    for ( i = 0; i<length; i++ ) {

    }   
    return 0;
}

if i want to print "my" "name" "is" and "geany" separate then what do I do. I was thinking to use a delimnator but i dont know how to do it in C

like image 991
larzgmoc Avatar asked Sep 13 '12 15:09

larzgmoc


People also ask

What can I use instead of strtok?

Use strtok_r(). It's the same behaviour as strtok, but allow you to work with multiple strings "simultaneously".

How do you split a string in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

What does strtok return if delimiter not found?

The first call in the sequence searches s for the first character that isn't contained in the current delimiter string sep. If no such character is found, then there are no tokens in s, and strtok() returns a NULL pointer.

Does strtok need to be freed?

strtok returns a pointer into the original buffer passed to it; you should not attempt to free it.


1 Answers

  1. start with a pointer to the begining of the string
  2. iterate character by character, looking for your delimiter
  3. each time you find one, you have a string from the last position of the length in difference - do what you want with that
  4. set the new start position to the delimiter + 1, and the go to step 2.

Do all these while there are characters remaining in the string...

like image 131
Nim Avatar answered Oct 06 '22 00:10

Nim