How do I get a substring in C?

时间:2016-04-04 16:53:57

标签: c string substring

For example if:

z = "xxxx; yyyy";

How can I get the substrings so that

x = "xxxx"

and

y = "yyyy"

where "xxxx" and "yyyy" can be any string of any length?

1 个答案:

答案 0 :(得分:4)

You don't get much of built-in strings in C, let alone substrings. When you need a substring, you build it yourself by copying relevant portions of the string into a properly allocated memory buffer, and then you null-terminate the result.

Here is an example:

char *c = "xxxx; yyyy";
char x[5], y[5];
memcpy(x, &c[0], 4);
x[4] = '\0';
memcpy(y, &c[6], 4);
y[4] = '\0';

Demo.