Standard string functions strtok
, strstr
, strchr
all will work, provided the surrounding code is correct as well. That is, if you want to search multiple times in the same source string, you need to point a Start-at pointer at the start of your source, and after each (succesful!) search update it to point after your delimiter. By default, strtok
will work fine for your purpose -- a single character delimiter. You can read about strtok
in any good reference (I'm not going to look it up for you).
In fact it is such a simple operation, I made this up just now. Other than vanilla strtok
, my strcpyUpTo
accepts any delimiter string. I could have used strstr
to first check, but I prefer copying right away. The strncmp
and strlen
inside the copy loop may be inefficient; then again, in general these low-level string operations should be pretty fast nevertheless.
#include <stdio.h>
#include <string.h>
char *strcpyUpTo (const char *source, char *dest, const char *delim)
{
while (*source && strncmp (source, delim, strlen(delim)))
*dest++ = *source++;
*dest = 0;
if (*source)
return (char *)(source+strlen(delim));
return (char *)source;
}
int main (void)
{
char *sentence = "Wisteria#any#Tunnel#any#Japan";
char stringA[50];
char stringB[50];
char stringC[50];
char *pDelim;
pDelim = strcpyUpTo (sentence, stringA, "#any#");
pDelim = strcpyUpTo (pDelim, stringB, "#any#");
pDelim = strcpyUpTo (pDelim, stringC, "#any#");
printf ("stringA = "%s"
", stringA);
printf ("stringB = "%s"
", stringB);
printf ("stringC = "%s"
", stringC);
return 0;
}
Addition
For an unknown number of substrings, you can use a while
loop such as the following. (For production code, it needs all kinds of checks. Left out for brevity, for clarity, and as exercise for the reader.) It's basically how you'd use strtok
as well.
char resultList[10][50];
int i, n_result;
pDelim = sentence;
n_result = 0;
do
{
pDelim = strcpyUpTo (pDelim, resultList[n_result], "#any#");
n_result++;
} while (*pDelim && n_result < 10);
printf ("number of strings: %d
", n_result);
for (i=0; i<n_result; i++)
printf ("string %d = "%s"
", i, resultList[i]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…