C question: How many %d and %s in a format string?

AgentEL

Golden Member
Jun 25, 2001
1,327
0
0
Is there an easy way to find out how many %d's, %s's are in a string.

For example:

count_specifier("arg1: %d, blah %d %s %s\n");

Should return 4.

Is there a function that does this already? I heard there was, but does anyone else know about this? I could do it the brute force way and count %'s, but I wanted to know if there was a more eloquent solution. Many thanks in advance.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
I have basically never used C string handling in "real life," but here's my whack at it:

int substr_count(const char * haystack, const char * needle) {
int count = 0;
const char * pos = haystack;

while(pos != '\0' && (pos = strstr(pos+1, needle)) != NULL)
count++;

return count;
}
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Tsk tsk... you forgot to look out for a preceeding percent sign ;). (Well, your function does what it claims, but not what the original poster wants).
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
%% is an escaped %, not \% (ctho's post originally said backslash).

Simply checking whether pos-1 is also a % won't do, since %%% would mess that up.

The answer is to either never use %%, or figure that one out yourself. ;) Text parsing is the janitorial work of programming.. not fun.