问题
How does one check the read in string for a substring in C?
If I have the following
char name[21];
fgets(name, 21, stdin);
How do I check the string for a series of substrings?
How does one check for a substring before a character? For example, how would one check for a substring before an =
sign?
回答1:
Be wary of strtok()
; it is not re-entrant. Amongst other things, it means that if you need to call it in one function, and then call another function, and if that other function also uses strtok()
, your first function is messed up. It also writes NUL ('\0'
) bytes over the separators, so it modifies the input string as it goes. If you are looking for more than one terminator character, you can't tell which one was found. Further, if you write a library function for others to use, yet your function uses strtok()
, you must document the fact so that callers of your function are not bemused by the failures of their own code that uses strtok()
after calling your function. In other words, it is poisonous; if your function calls strtok()
, it makes your function unreusable, in general; similarly, your code that uses strtok()
cannot call other people's functions that also use it.
If you still like the idea of the functionality - some people do (but I almost invariably avoid it) - then look for strtok_r()
on your system. It is re-entrant; it takes an extra parameter which means that other functions can use strtok_r()
(or strtok()
) without affecting your function.
There are a variety of alternatives that might be appropriate. The obvious ones to consider are strchr()
, strrchr()
, strpbrk()
, strspn()
, strcspn()
: none of these modify the strings they analyze. All are part of Standard C (as is strtok()
), so they are essentially available everywhere. Looking for the material before a single character suggests that you should use strchr()
.
回答2:
Use strtok() to split the string into tokens.
char *pch;
pch = strtok (name,"=");
if (pch != NULL)
{
printf ("Substring: %s\n",pch);
}
You can keep calling strtok()
to find more strings after the =
.
回答3:
You can use strtok
but it's not reentrant and it destroys the original string. Other (perhaps safer) functions to look into would be strchr
, strstr
, strspn
, and perhaps the mem*
variations. In general, I avoid strn*
variants because, while they do "boinds checking," they still rely on the nul terminator. They can fail on a valid string that just happens to be longer than you expected to deal with, and they won't actually prevent a buffer overrun unless you know the buffer size. Better (IMHO) to ignore the terminator and know exactly how much data you're working with every time the way the mem*
functions work.
来源:https://stackoverflow.com/questions/4981935/reading-user-input-and-checking-the-string