简体   繁体   中英

find biggest index of something in c

I want to write a function that finds the biggest index of the character in a string. But when the index is already found once, it may not return it.
For example :
word: "hello"
character: l
indexset={};
expected return value = 3

when I do this function again:
word: "hello"
character: l
indexset={3};
expected return value = 2

This is how I allocated spaces for my indexset:

*indexset = (int*) malloc(strlen(am->transposition)*sizeof(int));

In my code, that's enough space for each index of each character. My function to find the biggest index:

int findBiggestIndex(char karakter,char* woord,int* indexset, int *size){
    int i=0,index;
    for(i=0;i<strlen(woord);i++){
        if(karakter==woord[i] && !inArray(indexset,i,*size)){
            index=i;
            printf("%d",*size);
            indexset[*size]=index;
            (*size)++;
        }
    }
    return index;
}

And the method inArray():

#define TRUE 1
#define FALSE 0
int inArray(int* arr, int a, int size){
    int i=0;
    for(i=0;i<size;i++){
        if(arr[i]==a){
            return TRUE;
        }
        return FALSE;
    }
}

The method inArray is also declared before findBiggestIndex so that's not the problem. Please help

I want to write a function that finds the biggest index of the character in a string.

If you want to find the last occurrence of a character in a string...
loop through string and compare char elements:

Something like :

int findLastIndex(char *str, char c)
{
    int keep = 0, i, len;
    if(str)
    {
        len = strlen(str);

        for(i=0;i<len ;i++)
        {
            if(str[i] == c) keep = i;   
        }
        return keep;//0 means nothing found
    }
    return -1;//means problem with input string
}

int main(void)
{
     int cnt= findLastIndex("only 1 g in line", 'g');
     //cnt should return as 7 for these inputs

         cnt= findLastIndex("2 g's in line(g)", 'g');
     //cnt should return as 14 for these inputs
     return 0;
}  

literal string arguments:  
|0|1|2|3|4|5|6|7|8|9|0|1|2|3|4|5|
|o|n|l|y| |1| |g| |i|n| |l|i|n|e|
               ^  
|2| |g|'|s| |i|n| |l|i|n|e|(|g|)|
                             ^

Therefore, should see index as 7 for first arg, 14 for second arg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM