Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

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 162 views
1 answer 142 views
1 answer 140 views
1 answer 177 views
1 answer 155 views
1 answer 153 views
1 answer 143 views
...