Search code examples
cstringstring-lengthlongest-substring

C-Program Determine the largest substring in a char array without 'e' or 'E'


I have a problem as stated in the title. Here more details.

My Problem is:

a) develop a C-function which gets a char array as input parameteter and which determines the largest substring in this char array without 'e' 'E'. Print the length of that substring.

b) write main function to test a) function. use scanf("%[^\n]",...) or a loop with getchar()

EX: input : "you are one." .output : "you ar" length: 6


Solution

  • Improvement of answer form @ChartesL.:

    #include<stdio.h>
    int main(){
        char myStr[30];
        char *ptr;
        // read myStr from console
        ...
        char* delim = myStr;
        int longest = 0;
        char*longestSubStr = null;
    
        for(ptr=myStr; *ptr != '\0'; ptr++) 
        {  
           if(*ptr == 'e' || *ptr == 'E') 
           {
               int substrLength = ptr - delim;
               if(substrLength  > longest)
               {
                   longest = substrLength;
                   longestSubstr = delim;
               }
               delim = ptr+1;
           }      
        }
        // show longest length in longest
        // longest substring starts at longestSubStr, first 'longest' chars
        ...
    
        return 0;   
    }
    

    it remebers the last delimiter (either start of string, "e" or "E") and whenever a new delimiter is found, the length of the substring between two delimiters is calculated. Then determinest the longest of these lengths and remembers the longest substring found so far.