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,971 questions

51,913 answers

573 users

How to find the longest common string prefix in array of strings in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
   
#define ROWS 3
#define COLS 20

int compare_function(const void *a, const void *b) {
  return strcmp(a, b);
}

int min_length(char arr[][COLS]) {
    int min = strlen(arr[0]);

    for (int i = 1; i < ROWS; i++) {
        int size = strlen(arr[i]);
        if (size < min) min = size;
    }
    
    return min;
}

int main() {
    char arr[ROWS][COLS] = {"cartography", "carburettor", "carbonating"}; 
    
    qsort(arr, (size_t)ROWS, COLS, compare_function);
    
    int m_length = min_length(arr);

    int i = 0;
    while (i < m_length && arr[0][i] == arr[ROWS - 1][i]) 
        i++; 

    printf("Longest common prefix: %.*s\n", i, arr[0]);

    return 0;
}




/*
run:

Longest common prefix: car

*/

 



answered Mar 3, 2021 by avibootz
...