我有一个字符串定义为:
char *str如何检查字符串是否与格式匹配:
x-y-z其中x、y和z都是int的类型。
例如:字符串1-2-4应该是有效的,而"1-2*3"、"1-2"、"1-2-3-4"则无效。
发布于 2016-07-30 09:54:09
如果您需要更多的信息,而不仅仅是匹配,那么您可以使用循环遍历字符串。我会给你一些初始代码。
int i = 0;
int correct = 1;
int numberOfDashes = 0;
while(correct && i < strlen(str)) {
if(isdigit(str[i])) {
}
else {
if(str[i] == '-') {
numberOfDashes++;
}
}
i++;
} 发布于 2016-07-30 09:50:18
实现所需内容的一个简单方法是使用scanf()并检查返回的值。有点像
ret = scanf("%d-%d-%d", &x, &y, &z);
if (ret == 3) {// match};用简单的方法就行了。
但是,这种方法不适用于多种数据类型和较长的输入,只适用于固定格式。对于更复杂的场景,您可能需要考虑使用regex库。
发布于 2016-07-30 09:55:42
和苏拉夫的回答一样。
int check( char t[] )
{
int a, b, c, d;
return sscanf( t, "%d-%d-%d-%d", &a, &b, &c, &d ) == 3;
}
int main()
{
char s[] = "1-2-4";
char t[] = "1-2-3-4";
printf( "s = %s, correct format ? %s\n", s, check( s ) ? "true" : "false" ); // <-- true
printf( "t = %s, correct format ? %s\n", s, check( t ) ? "true" : "false" ); // <-- false
}https://stackoverflow.com/questions/38672532
复制相似问题