1

I want to check if the characters of a string are in this form:

hw: + one numeric character + , + one numeric character

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

Et cetera

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

I found strncmp(arg, "hw:", 3) but that only checks the first 3 characters.

1
  • For just 6 chars like that it's fairly trivial to just check every character. Commented Jun 29, 2013 at 2:49

3 Answers 3

4

It's tempting to use strlen() and 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...

This works particularly well if you need to know what the two digits are, not merely that the format is correct. However, you can also pull the digits out by fixed position, so that is not crucial. It also upgrades gracefully (though not without change) if you need to allow for "hw:12,25" in the future.

Sign up to request clarification or add additional context in comments.

Comments

3

strncmp(arg, "hw:", 3) is a good start (remember that the function returns zero when the match is found). Next, you need to check that

  • character 3 is a digit,
  • character 4 is a comma, and
  • character 5 is a digit.

This results in the following expression:

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

Note the use of isdigit(int) to test that a character is a digit.

If the numbers could span more than a single digit, you could use sscanf: this would also let you retrieve the values:

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

1 Comment

Note that the %d notations mean that hw: 3, 4 would be allowed as valid. So would hw:-34,+45. You can preclude those with a length check.
1

The GNU C library supports regular expressions. If you don't want to learn regular expressions, you can just repeatedly use strncmp as well as functions from the ctype.h header.

1 Comment

A full regular expression is a fairly big sledgehammer for a fairly small nut. Certainly it would work, and if you're already using regular expressions would be sensible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.