andre
andre

Reputation: 175

Tokenize a c string

I'm trying to get the string thet's after /xxx/, there is a must be forward slashes, two of them, then the string that I need to extract. Here is my code, but I don't know where to set the null terminator, there is a math problem here

char str[100] = "/709/usr/datapoint/nviTemp1";
char *tmp;
char token[100];

tmp = strchr(str+1, '/');
size_t len = (size_t)(tmp-str)+1;
strncpy(token, str+len, strlen(str+len));
strcat(token,"\0");

I want to extract whatever after /709/ which is usr/datapoint/nviTemp1

Note that /709/ is variable and it could be any size but for sure there will be two forward slashes.

Upvotes: 1

Views: 151

Answers (4)

ameyCU
ameyCU

Reputation: 16607

You can make use of sscanf-

sscanf(str,"%*[/0-9]%s",token);  
 /* '/709/' is read and discarded and remaining string is stored in token */

token will contain string "usr/datapoint/nviTemp1" .

Working example

Upvotes: 1

Enzo Ferber
Enzo Ferber

Reputation: 3094

You can use a counter and a basic while loop:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    if (argc < 2) return 0;

    char *s = argv[1];
    char slash = '/';
    int slash_count = 0;

    while (slash_count < 2 && *s)
        if (*s++ == slash) slash_count++;

    printf("String: %s\n", s);

    return 0;
}

Then you can do whatever you want with the s pointer, like duplicating it with strdup or using strcat, strcpy, etc...

Outputs:

$ ./draft /709/usr/datapoint/nviTemp1
String: usr/datapoint/nviTemp1
$ ./draft /70905/usr/datapoint/nviTemp1
String: usr/datapoint/nviTemp1

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

Simple improvement:

char str[100] = "/709/usr/datapoint/nviTemp1";
char *tmp;
char token[100];

tmp = strchr(str+1, '/');
if (tmp != NULL) strncpy(token, tmp + 1, sizeof(token)); else token[0] = '\0';

tmp points the slash after "/709", so what you want is right after there. You don't have to calculate the length manually.

Moreover, strncpy copies at most (third argument) characters, so it should be the length of the destination buffer.

Upvotes: 1

abelenky
abelenky

Reputation: 64682

If you know for sure that the string starts with `"/NNN/", then it is simple:

char str[100] = "/709/usr/datapoint/nviTemp1";
char token[100];
strcpy(token, str+5);  // str+5 is the first char after the second slash.

If you need to get everything after the second slash:

char str[100] = "/709/usr/datapoint/nviTemp1";
char token[100];
char* slash;
slash = strchr(str, '/');     // Expect that slash == str
slash = strchr(slash+1, '/'); // slash is second slash.
strcpy(token, slash+1);      // slash+1 is the string after the second slash.

Upvotes: 1

Related Questions