PDP
PDP

Reputation: 181

how to extract a substring from a string, if the length of string is unknown

Lets say I have string1 = "DDD DXXXX" string2 = "DDXXXX" string3 = "DXXXX"

and if i want to extract XXXX all the time, then what is the best way in c? substr, strncpy, strndup everything needs a starting position.

Is regex the only option?

Upvotes: 0

Views: 1999

Answers (2)

hmjd
hmjd

Reputation: 121971

Use strstr() to locate the "XXXX":

char string1[] = "DDXXXX";
char* xxxx_ptr = strstr(string1, "XXXX");
if (xxxx_ptr)
{
    /* Do something. */
}

Upvotes: 2

Attila
Attila

Reputation: 28762

If you know it is always at the end and of a fixed length, you can calculate its starting position by calculating the length of the string (strlen()) and subtracting the fixed length.

This assumes the substring is always part of the strings you examine

Upvotes: 1

Related Questions