A simple way to obtain a single token that does not modify the original string is to use two calls to strcspn()
establishing a start-pointer to the first delimiter ('$'
in this case) and an end-pointer to the last character in the token (the character before the second '$'
or end-of-string if no second '$'
is present). You then validate that characters exist between the start-pointer and end-pointer and use memcpy()
to copy the token.
A short example is:
#include <stdio.h>
#include <string.h>
int main (void) {
char txt[80] = "Some text before $11/01/2017$",
*sp = txt + strcspn (txt, "$"), /* start ptr to 1st '$' */
*ep = sp + strcspn (*sp ? sp + 1 : sp, "$
"), /* end ptr to last c in token */
result[sizeof txt] = ""; /* storage for result */
if (ep > sp) { /* if chars in token */
memcpy (result, sp + 1, ep - sp); /* copy token to result */
result[ep - sp] = 0; /* nul-termiante result */
printf ("%s
", result); /* output result */
}
else
fputs ("no characters in token
", stderr);
}
(note: the ternary simply handles the case txt
is the empty-string. The '
'
is added as part of the 2nd delimiter to handle strings past from fgets()
or POSIX getline()
where no second '$'
is present and '
'
is the last character in the string.)
Works also with any combination of empty-string, zero, one or two '$'
and does not modify original so is safe for use with String-Literals.
Example Use/Output
$ ./bin/single_token
11/01/2017
Let me know if you have additional questions.
Variation Allowing Valid Empty-String as Result
A neat improvement provided by @chqrlie providing a test of (*sp == '$')
instead of (ep > sp)
would allow the empty-string (no characters in token) to be a valid result -- I agree). The change would be:
if (*sp == '$') { /* if chars in token */
memcpy (result, sp + 1, ep - sp); /* copy token to result */
result[ep - sp] = 0; /* nul-termiante result */
printf ("%s
", result); /* output result */
}
So if you want to consider an empty token (like an empty field in a .csv, e.g. "one,,three,four"
) to be a valid token, use this alternative.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…