is there a function that determins the position of a certain character in a character array?
is there a function that determins the position of a certain character in a character array?
In a perfect world every dog would have a home and every home would have a dog.
Visit My Web Site, Canine Programming
I use Win32 API
I seem to remember strchr()....Originally posted by canine
is there a function that determins the position of a certain character in a character array?
This gives a pointer to the first 'o' in the phraseCode:char str[] = "Hello World"; char *ptrChar = strchr(str,'o'); printf("%s",ptrChar);
Last edited by Fordy; 01-23-2002 at 05:49 PM.
i need to know the actual position though
.................................................. .
char str[]="abcdefg";
int pos;
pos = ?????(str,'e');
<pos = 4>
In a perfect world every dog would have a home and every home would have a dog.
Visit My Web Site, Canine Programming
I use Win32 API
Okay, so you have a pointer to the first occourance of the element in the string...
And you have a pointer to beginning of the string...
And you want the distance to that element from the beginning of the string?
Subtract.
Callou collei we'll code the way
Of prime numbers and pings!
Originally posted by canine
i need to know the actual position though
.................................................. .
char str[]="abcdefg";
int pos;
pos = ?????(str,'e');
<pos = 4>Code:char str[] = "Hello World"; int x,pos = 0; for(x = 0; x < strlen(str);x++){ if(str[x] == 'o'){ pos = x; break;} } printf("o was found at position %d",pos); return 0;
One restriction with this solution: you can't search for a NULL since that is the character that signals the caller that we didn't find the search character.Code:#include <stdio.h> char FindChar(char *p, char c, int *i); int main() { char MyString[31] = "this is my string"; char ch = 'm'; int location = 0; if (FindChar(MyString, ch, &location)) printf("found %c at %d", ch, location); else printf ("character not found"); return 0; } char FindChar(char *p, char c, int *i) { while (*p) { if (*p == c) break; (*i)++; p++; } return *p; // return the NULL if search character not found }
> char str[]="abcdefg";
> int pos;
> pos = ?????(str,'e');
Would be
Code:char str[]="abcdefg"; int pos; char *p = strchr( str, 'e' ); if ( p != NULL ) { pos = p - str; } else { pos = -1; // something not found }