David Warner wrote:
Greetings!
In looking into some C coding, I am looking for the C function that will
search for multiple of a same character in a string.
For Instance:
char str[80] = "We the people of the United States";
strchr will be successful if i am looking for the "U". It returns a
successful condition.
However, if I want to parse down the string and look for each occurance
of "o", I should either get a count of 2 or the pointer moves to the
first occurance.
I understand the "count of 2" piece, but I'm not at all
sure what you mean by "or the pointer moves to the first
occurance [sic]."
Is there a standard C function that returns the value(s) i am looking
for or is this something I need to write myself?
You could use strchr() in a loop, finding one target
character each time (except the last):
int count = 0;
char *where = str;
while ((where = strchr(where, 'o')) != NULL) {
++count;
++where;
}
Personally, I'd probably opt for the simpler
for (where = str; *where != '\0'; ++where) {
if (*where == 'o')
++count;
}
There's a chance the former version might be faster, especially
if `str' is very long and contains few occurrences of the target
character. However, the difference is unlikely to be significant
in the face of whatever else the program is doing (I/O, for
example), while the second is easier to read and perhaps harder
to botch.
--
Er*********@sun.com