我想确保我的字符串(由用户键入)仅包含字母和那些特殊字符(-, ,_,,)
。
在C中怎么可能?
预先感谢!
答案 0 :(得分:0)
从Filtering a character out of a string in C和@FiddlingBits comment得到启发,这是保持字母和所需字符的可能解决方案:
#include <ctype.h>
#include <string.h>
void filter_chars(const char *string, char *result, const char *keep)
{
int bad, j = 0;
int nkeep;
nkeep = (int) strlen(keep);
for (int i = 0; string[i] != '\0'; i++)
{
if (isalpha(string[i]))
{
result[j++] = string[i];
continue;
}
for (int k = 0; k < nkeep; k++)
if (string[i] == keep[k])
{
result[j++] = string[i];
break;
}
}
result[j] = '\0';
}