Inês
Inês

Reputation: 747

Detect substring in specific format

What is the simplest way to detect a substring in a specific format?

For example, consider the string in C

"[random characters/symbols] a-b-c [random characters/symbols]"

Is there a function in C that allows me to detect the substring in the format "%s-%s-%s"?

Upvotes: 1

Views: 132

Answers (2)

chux
chux

Reputation: 154255

Try starting at various points within the string until success.

"%*[^- ] look for a sub-string that does not contain a '-' nor space.

"%n Record the offset in the scan.

#include<stdio.h>

int main(void) {
  char *s = "[random characters/symbols] a-b-c [random characters/symbols]";

  while (*s) {
    int n = 0;
    sscanf(s, "%*[^- ]-%*[^- ]-%*[^- ]%n", &n);
    if (n) {
      printf("Success '%.*s'\n", n, s);
      break;
    }
    s++;
  }
  return 0;
}

Output

Success 'a-b-c'

Upvotes: 3

markshancock
markshancock

Reputation: 690

Use strchr() or strnchr() if you have it to detect a literal string (no pattern matching). The function strnchr() is better because you can specify a max length to protect against a string with a missing null terminator; but, it is not ANSI so not all languages have it. If you use strchr() make sure you protect against a missing null terminator.

You can use regcomp() to do a regular expressions search the string. See regex in C language using functions regcomp and regexec toggles between first and second match

Upvotes: 1

Related Questions