Search code examples
c++stringsequences

length of sub-sequence in the string


I need to implement lastSeq function,which gets as argument string str and char chr and returns the length of last sequence of repeated chr (the sequence can be of any length) for example: lastSeq("abbaabbbbacd",'a') should return 1
lastSeq("abbaabbbbacd",'b') should return 4 lastSeq("abbaabbbbacd",'t') should return 0

Is there C++ function which can solve it?


Solution

  • int lastSeq(char *str, char chr)  
    {  
        int i = strlen(str);  
        int l = 0;  
    
        while(--i>=0)  
           if(*(str + i) == chr && ++l)  
              break;
    
        while(--i>=0 && chr == *(str + i) && ++l);  
    
        return l;  
    }