Wednesday, August 11, 2010

How to find first\last occurance of a character in a string without using strchr()/strrchr() function in C?

How to find first\last occurance of a character in a string without using strchr()/strrchr() function in C?How to find first\last occurance of a character in a string without using strchr()/strrchr() function in C?
Just write your own versions of strchr and strrchr.


You need a loop that goes from the first to last char, or last to first char.


Compare the current char to the one you are looking for. If found, return the where found.How to find first\last occurance of a character in a string without using strchr()/strrchr() function in C?
If you don't want to be searching for it using another function, then something like this to find the first occurence





char searchletter = 'o';


char* buffer = ';Your string here';;


bool found = false;


int pos = -1;


for (int i = 0; i %26lt; strlen(buffer) %26amp;%26amp; (!found); i ++)


if (buffer[i] == searchletter)


{


found = true;


pos = i;


}





should work with pos being the position of the first one, or -1 if it didn't find one.


As for the last occurence, Id suggest this





char searchletter = 'e';


char* buffer = ';Your string here';;


int pos = -1;


for (int i = 0; i %26lt; strlen(buffer); i ++)


if (buffer[i] == searchletter)


{


pos = i;


}





and pos should have the last occurence, or -1 if it didn't occur

No comments:

Post a Comment