Sunday, August 2, 2009

C program recursive method (find the character index in the string)?

str = "Hello world"


ch = "w"


use recursive method, no string.h function


return 'w' index = 6





int findIndexString(char str[ ], char ch)

C program recursive method (find the character index in the string)?
again, like before! I really hv too much time in my hands today :-p





#include %26lt;stdio.h%26gt;





int findIndexString(char str[], char ch) {


int pos;


if (*str=='\0') {


return -1;


}


if(*str==ch) {


return 0;


}


pos = findIndexString(++str, ch);


if (pos%26lt;0) {


return pos;


} else {


return pos+1;


}


}


int main() {


char str[25]="hello world";


int pos = findIndexString(str, 'h');


printf("The position is %d\n", pos);


}
Reply:Hello,





I suppose this is just for fun? If so, ok.





Else please note It is particularly inefficient to use recursiveness for such low level functions. You put the system under heavy strain due to call stack adjustments needed to accomodate the numerous function calls (passing variables).
Reply:int findIndexString(char str[],char ch)


{


static int i=0;


if(*str =='\0')


return 0;


else if(*str == ch)


return i;


else{


i++;


return findIndexString(++str,ch);


}





}


No comments:

Post a Comment