用于检查字符串字符是否为特定形式的函数

时间:2013-06-29 02:44:38

标签: c string

我想检查一下字符串的字符是否是这种形式:

hw: +一个数字字符+ , +一个数字字符

hw:0,0 
hw:1,0
hw:1,1
hw:0,2

Et cetera

/* 'hw:' + 'one numeric character' + ',' + 'one numeric character' */

我找到strncmp(arg, "hw:", 3),但只检查前3个字符。

3 个答案:

答案 0 :(得分:4)

使用strlen()sscanf()

很有吸引力
char *data = "hw:1,2";
char digit1[2];
char digit2[2];

if (strlen(data) == 6 && sscanf(data, "hw:%1[0-9],%1[0-9]", digit1, digit2) == 2)
    ...then the data is correctly formatted...
    ...and digit1[0] contains the first digit, and digit2[0] the second...

如果你需要知道这两个数字是什么,这不仅仅是格式正确。但是,您也可以通过固定位置拉出数字,因此这并不重要。如果您将来需要允许"hw:12,25",它也会优雅地升级(尽管并非没有变化)。

答案 1 :(得分:3)

strncmp(arg, "hw:", 3)是一个好的开始(请记住,当找到匹配项时,函数返回零)。接下来,您需要检查

  • 字符3是一个数字,
  • 字符4是逗号,
  • 字符5是一个数字。

这导致以下表达式:

if (!strncmp(arg, "hw:", 3) && isdigit(arg[3]) && arg[4] == ',' && isdigit(arg[5])) {
    ...
}

请注意使用isdigit(int)来测试字符是否为数字。

如果数字可以跨越多个数字,您可以使用sscanf:这也可以让您检索值:

int a, b;
if (sscanf(arg, "hw:%d,%d", &a, &b) == 2) {
    ...
}

答案 2 :(得分:1)

GNU C库支持regular expressions。如果您不想学习正则表达式,可以重复使用strncmp以及ctype.h标题中的函数。