我想检查字符串中的字符是否采用以下格式:
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个字符。

最佳答案

很容易使用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"的话,它还可以优雅地升级(尽管不是没有更改)。

关于c - 检查字符串的字符是否为特定格式的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17376190/

10-12 03:07