2016-07-30 128 views
0

特定的格式为:检查是否匹配字符串我有一个字符串定义

char *str 

我如何检查,以验证是否字符串匹配的格式为:

x-y-z 

其中,x,y和z都是int

例如:字符串1-2-4应该有效,而"1-2*3","1-2","1-2-3-4"无效。

+2

你有什么试过自己?那是怎么做的,或者没有做到这一点?你的程序有什么问题?另请[请阅读如何提出好问题](http://stackoverflow.com/help/how-to-ask),并学习如何创建[最小,完整和可验证示例](http:// stackoverflow .COM /帮助/ MCVE)。 –

+0

仅使用纯C,还是例如正则表达式库的一个选项? – usr2564301

+0

我认为你应该使用正则表达式来匹配你的字符串。做一些谷歌搜索它,你会发现很多的例子约翰 – baliman

回答

0

如果您需要更多信息而不仅仅是匹配,那么您可以使用循环遍历字符串。我会给你一些入门代码。

int i = 0; 
int correct = 1; 
int numberOfDashes = 0; 
while(correct && i < strlen(str)) { 
    if(isdigit(str[i])) { 

    } 
    else { 
    if(str[i] == '-') { 
     numberOfDashes++; 
    } 
    } 
    i++; 
} 
3

一个简单的方法来实现你想要的是使用scanf()并检查返回的值。像

ret = scanf("%d-%d-%d", &x, &y, &z); 
    if (ret == 3) {// match}; 

会做一个简单的方法罚款。

虽然这种方法不适用于多种数据类型和较长的输入,但只适用于固定格式。对于更复杂的场景,您可能需要考虑使用正则表达式库。

+3

它不会为“1-2-3-4”虽然.. – artm

+4

(也许更好的建议'sscanf'?) – usr2564301

+2

测试为'-1- 2-3' – BLUEPIXY

0

与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 
} 
+2

测试为'“1-2-4-”' – BLUEPIXY

0

您可以使用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; 
} 

Demo on Ideone

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; 
} 

Demo on Ideone

为了规避这一点,你需要使用regular expressions作为t他人已经说过了。

相关问题