search for occurance of character in certain position in a string

M

magix

How can I search for occurance of a character in certain position of a
string
I checked function strchr, but doesn't option to specify position.

Thanks.

Regards,
Magix
 
K

Keith Thompson

magix said:
How can I search for occurance of a character in certain position of a
string
I checked function strchr, but doesn't option to specify position.

If you're checking a certain position, it's not really a search, is it?

It sounds like you're looking for something that will tell you, for
example, whether or not the character 'C' occurs in the third position
(position 2) in the string "ABCDE", regardless of whether it also
occurs anywhere else. If so, all you need is a single comparison. If
not, please clarify what you're asking for.
 
P

Peter Nilsson

magix said:
How can I search for occurance of a character
in certain position of a string

if (strlen(s) > n && s[n] == ch)
/* yes, char ch at position n in s */
 
U

user923005

How can I search for occurance of a character in certain position of a
string
I checked function strchr, but doesn't option to specify position.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

long location(char *string, int ch)
{
char *where = strchr(string, ch);
long index = -1;
if (where) {
index = where - string;
}
return index;
}
int main(void)
{
char string[] = "Hello, my name is skinner the
grinner! What's yours?";
long loc;
loc = location(string, '!');
if (loc >= 0) {
printf("position is %ld\n", loc);
putchar(string[loc]);
} else {
puts("Not found.");
}
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top