There are a large number of ways to approach the problem. From walking a pair of pointers down the string to locate the delimiters, and a large number of string functions provided in string.h
. You can make use of character search functions such as strchr
or string search functions like strpbrk
, you can use tokenizing functions like strtok
, etc...
Look over and learn from them all. Here is an implementation with strpbrk
and a pointer difference. It is non-destructive, so you need not make a copy of the original string.
#include <stdio.h>
#include <string.h>
int main (void) {
const char *line = "'foobar'|cat";
const char *delim = "'"; /* delimiter, single quote */
char *p, *ep;
if (!(p = strpbrk (line, delim))) { /* find the first quote */
fprintf (stderr, "error: delimiter not found.\n");
return 1;
}
p++; /* advance to next char */
ep = strpbrk (p, delim); /* set end pointer to next delim */
if (!p) { /* validate end pointer */
fprintf (stderr, "error: matching delimiters not found.\n");
return 1;
}
char substr[ep - p + 1]; /* storage for substring */
strncpy (substr, p, ep - p); /* copy the substring */
substr[ep - p] = 0; /* nul-terminate */
printf ("\n single-quoted string : %s\n\n", substr);
return 0;
}
Example Use/Output
$ ./bin/substr
single-quoted string : foobar
Without Using string.h
As mentioned above, you can also simply walk a pair of pointers down the string and locate your pairs of quotes in that manner as well. For completeness, here is an example finding multiple quoted strings within 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++) { /* for each char in line */
if (!sp && *p == delim) /* find 1st delim */
sp = p, sp++; /* set start ptr */
else if (!ep && *p == delim) /* find 2nd delim */
ep = p; /* set end ptr */
if (sp && ep) { /* if both set */
char substr[ep - sp + 1]; /* declare substr */
for (i = 0, p = sp; p < ep; p++)/* copy to substr */
substr[i++] = *p;
substr[ep - sp] = 0; /* nul-terminate */
printf ("single-quoted string : %s\n", substr);
sp = ep = NULL;
}
}
return 0;
}
Example Use/Output
$ ./bin/substrp
single-quoted string : foobar
single-quoted string : mousebar
Look all the answers over and let us know if you have any questions.