How to get all palindrome substrings in a string with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
 
char *get_substring(char *s, int i, int j) {
    int len = j - i;
    char *sub = (char *)malloc((len * sizeof(char)) + 1);
    sub[len] = '\0';
    strncpy(sub, s + i, len); 
     
    return sub;
}
bool is_palindrome(char *s, int i, int j) {
    char *rev = get_substring(s, i, j);
    strrev(rev);
     
    char *tmp_s = get_substring(s, i, j);
     
    bool b = false;
    if (strcmp(tmp_s, rev) == 0 && strlen(tmp_s) >= 2) {
        b = true;
    }
     
    free(rev);
    free(tmp_s);
     
    return b;
}
 
int main() {
    char s[] = "abaab";
      
    for (int i = 0; i < strlen(s); i++) { 
        for (int j = i + 1; j <= strlen(s); j++) { 
             if (is_palindrome(s, i, j)) {
                char *sub = get_substring(s, i, j);
                puts(sub);
                free(sub);
             }
        }
    }
     
    return 0;
}
 
  
  
/*
run:
  
aba
baab
aa
 
*/

 

 



answered Oct 21, 2019 by avibootz
edited Oct 22, 2019 by avibootz

Related questions

1 answer 186 views
1 answer 163 views
1 answer 156 views
1 answer 235 views
1 answer 179 views
1 answer 180 views
1 answer 169 views
...