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
using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static string LongestCommonPrefix(string input) {
        if (string.IsNullOrWhiteSpace(input))
            return "";

        // Split by non‑word characters (same as Java's split("\\W+"))
        var words = Regex.Split(input.ToLower(), "\\W+")
                         .Where(w => w.Length > 0)
                         .ToArray();

        if (words.Length == 0)
            return "";

        string prefix = words[0];

        for (int i = 1; i < words.Length; i++) {
            while (!words[i].StartsWith(prefix)) {
                prefix = prefix.Substring(0, prefix.Length - 1);
                if (prefix.Length == 0)
                    return "";
            }
        }

        return prefix;
    }

    static void Main()
    {
        string s1 = "The lowly inhabitants of the lowland were surprised to see the lower branches.";
        Console.WriteLine($"LCP: '{LongestCommonPrefix(s1)}'");

        string s2 = "unclear, uncertain, unexpected";
        Console.WriteLine($"LCP: '{LongestCommonPrefix(s2)}'");
    }
}



/*
run:

LCP: ''
LCP: 'un'

*/

 



answered 3 days ago by avibootz

Related questions

...