. , , , string.h. , strchr , strpbrk, , strtok ..
. strpbrk . , .
#include <stdio.h>
#include <string.h>
int main (void) {
const char *line = "'foobar'|cat";
const char *delim = "'";
char *p, *ep;
if (!(p = strpbrk (line, delim))) {
fprintf (stderr, "error: delimiter not found.\n");
return 1;
}
p++;
ep = strpbrk (p, delim);
if (!p) {
fprintf (stderr, "error: matching delimiters not found.\n");
return 1;
}
char substr[ep - p + 1];
strncpy (substr, p, ep - p);
substr[ep - p] = 0;
printf ("\n single-quoted string : %s\n\n", substr);
return 0;
}
/
$ ./bin/substr
single-quoted string : foobar
Without using string.h
As mentioned above, you can also just go a couple of pointers down the line and find your quotes pairs in the same way. For completeness, here is an example of finding several quoted lines in a single line:
#include <stdio.h>
int main (void) {
const char *line = "'foobar'|cat'mousebar'sum";
char delim = '\'';
char *p = (char *)line, *sp = NULL, *ep = NULL;
size_t i = 0;
for (; *p; p++) {
if (!sp && *p == delim)
sp = p, sp++;
else if (!ep && *p == delim)
ep = p;
if (sp && ep) {
char substr[ep - sp + 1];
for (i = 0, p = sp; p < ep; p++)
substr[i++] = *p;
substr[ep - sp] = 0;
printf ("single-quoted string : %s\n", substr);
sp = ep = NULL;
}
}
return 0;
}
Usage / Output Example
$ ./bin/substrp
single-quoted string : foobar
single-quoted string : mousebar
See all the answers and let us know if you have any questions.
source
share