特定的格式为:检查是否匹配字符串我有一个字符串定义
char *str
我如何检查,以验证是否字符串匹配的格式为:
x-y-z
其中,x,y和z都是int。
例如:字符串1-2-4
应该有效,而"1-2*3"
,"1-2"
,"1-2-3-4"
无效。
特定的格式为:检查是否匹配字符串我有一个字符串定义
char *str
我如何检查,以验证是否字符串匹配的格式为:
x-y-z
其中,x,y和z都是int。
例如:字符串1-2-4
应该有效,而"1-2*3"
,"1-2"
,"1-2-3-4"
无效。
如果您需要更多信息而不仅仅是匹配,那么您可以使用循环遍历字符串。我会给你一些入门代码。
int i = 0;
int correct = 1;
int numberOfDashes = 0;
while(correct && i < strlen(str)) {
if(isdigit(str[i])) {
}
else {
if(str[i] == '-') {
numberOfDashes++;
}
}
i++;
}
一个简单的方法来实现你想要的是使用scanf()
并检查返回的值。像
ret = scanf("%d-%d-%d", &x, &y, &z);
if (ret == 3) {// match};
会做一个简单的方法罚款。
虽然这种方法不适用于多种数据类型和较长的输入,但只适用于固定格式。对于更复杂的场景,您可能需要考虑使用正则表达式库。
与Sourav的答案一致。
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
}
测试为'“1-2-4-”' – BLUEPIXY
您可以使用sscanf
作为您的特定字符串示例。
int main()
{
int x,y,z;
char *str="1-2-4";
int a = sscanf(str, "%d-%d-%d", &x, &y, &z);
printf("%s", (a == 3) ? "Correct format":"Incorrect format");
return 0;
}
而sscanf
格式不会为指定的字符串工作:
int main()
{
int x,y,z;
char *str="1-2*3"; //or "1-2" or ""1-2-3-4""
int a = sscanf(str, "%d-%d-%d", &x, &y, &z);
printf("%s", (a == 3) ? "Correct format":"Incorrect format");
return 0;
}
为了规避这一点,你需要使用regular expressions作为t他人已经说过了。
你有什么试过自己?那是怎么做的,或者没有做到这一点?你的程序有什么问题?另请[请阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask),并学习如何创建[最小,完整和可验证示例](http:// stackoverflow .COM /帮助/ MCVE)。 –
仅使用纯C,还是例如正则表达式库的一个选项? – usr2564301
我认为你应该使用正则表达式来匹配你的字符串。做一些谷歌搜索它,你会发现很多的例子约翰 – baliman