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.

40,276 questions

52,302 answers

573 users

How to find the longest common prefix of all the words in a string with C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define MAX_WORDS 64
#define MAX_LEN   128

// Extract lowercase words from a string
int extract_words(const char *s, char words[][MAX_LEN]) {
    int count = 0, i = 0, j = 0;

    while (s[i]) {
        if (isalpha(s[i])) {
            j = 0;
            while (isalpha(s[i])) {
                words[count][j++] = tolower(s[i++]);
            }
            words[count][j] = '\0';
            count++;
        } else {
            i++;
        }
    }
    return count;
}

// Longest common prefix of two strings
void lcp_two(const char *a, const char *b, char *out) {
    int i = 0;
    while (a[i] && b[i] && a[i] == b[i]) {
        out[i] = a[i];
        i++;
    }
    out[i] = '\0';
}

// LCP of all words
void longest_common_prefix(const char *s, char *result) {
    char words[MAX_WORDS][MAX_LEN];
    int n = extract_words(s, words);

    if (n == 0) {
        result[0] = '\0';
        return;
    }

    strcpy(result, words[0]);

    char temp[MAX_LEN];
    for (int i = 1; i < n; i++) {
        lcp_two(result, words[i], temp);
        strcpy(result, temp);
        if (result[0] == '\0') return;
    }
}

int main() {
    char result[MAX_LEN];

    char s1[] = "The lowly inhabitants of the lowland were surprised to see the lower branches.";
    longest_common_prefix(s1, result);
    printf("LCP: '%s'\n", result);   // prints ""

    char s2[] = "unclear uncertain unexpected";
    longest_common_prefix(s2, result);
    printf("LCP: '%s'\n", result);   // prints "un"
}



/*
run:

LCP: ''
LCP: 'un'

*/

 



answered 3 days ago by avibootz

Related questions

...