Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the substr this way in c?

Tags:

c

string

/^[^\s]+\s([^\s]+)\s/

In PHP,I can use regex to get the substr by $1,

how should I do it in C?

It's better if can do it without regex,though.

UPDATE

Put simply, how do I get werwerur out of swerwer werwerur y (the second)?

like image 283
httpinterpret Avatar asked Oct 14 '22 06:10

httpinterpret


1 Answers

I recommend to use strchr() - it is very fast to find characters in strings

#include <string.h>
..
char str[] = "swerwer werwerur y";
char *p1 = NULL,*p2 = NULL;

p1 = strchr(str,' ');
p1++;
p2 = strchr(p1,' ');
if(p2) *p2 = 0;

printf("found: %s\n", p1);

if you have multiple delimiters, you can use strtok_r() or strpbrk() as in example below:

    char str[] = "swerwer ., werwerur + y";
    const char *dlms = " .,+";
    char *p1 = NULL,*p2 = NULL;

    p1 = strpbrk(str,dlms);
    while(strchr(dlms,*p1)) p1++;
    p2 = strpbrk(p1,dlms);
    if(p2) *p2 = 0;

    printf("found: %s\n", p1);

(should cleanup code: in case if strpbrk returns NULL)

like image 119
Oleg Razgulyaev Avatar answered Oct 19 '22 03:10

Oleg Razgulyaev