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

51,662 answers

573 users

How to merge two strings based on shared suffix and prefix in C#

1 Answer

0 votes
using System;

class Program
{
    public static string MergeOnOverlap(string a, string b)
    {
        int lenA = a.Length;
        int lenB = b.Length;
    
        int maxPossibleverlapLen = Math.Min(lenA, lenB);
    
        int overlap = 0;
    
        // Try longest overlap first
        for (int len = maxPossibleverlapLen; len > 0; len--) {
            if (string.Compare(a, lenA - len, b, 0, len) == 0) {
                overlap = len;
                break;
            }
        }
    
        return a + b.Substring(overlap);
    }


    static void Main()
    {
        string a = "fantasy time travel technology";
        string b = "technology extraterrestrial life";

        Console.WriteLine(MergeOnOverlap(a, b));

    }
}



/*
run:

fantasy time travel technology extraterrestrial life

*/

 



answered Jan 23 by avibootz
edited 6 days ago by avibootz
...