Home > Software engineering >  How to compare two strings in C# where the beginning part of one is the end of the other
How to compare two strings in C# where the beginning part of one is the end of the other

Time:06-21

I have two strings, e.g.:

str1 = "CGGCAGTGGTAGTCTGAG" 
str2 = "TGAGCGCGCGCGCGCGCG"

I want to get the two strings same part "TGAG"

CodePudding user response:

I hope this helps you!

using System;
 

class string_comparison_equals
 
{
    static void Main()
 
    {
        string str1 = "CGGCAGTGGTAGTCTGAG"; 
        string str2 = "TGAGCGCGCGCGCGCGCG";

 
        if (String.Equals(str1[-1:-4], str2[0:3])) or (String.Equals(str1[0:3], str2[-1:-4]))
        {
            Console.WriteLine("The strings have the same beginning and end");
        }
        else
        {
            Console.WriteLine("The strings are different");
        }
 
        Console.ReadLine();
 
    }
 
}

The result should be:

The strings have the same beginning and end

CodePudding user response:

Yes?

public static string GetMatchPart(string str1, string str2)
{
    for (int i = str1.Length; i >= 0; i--)
    {
        for (int j = str2.Length; j >= 0; j--)
        {
            if (str1.StartsWith(str2.Substring(0, j)))
            {
                return str2.Substring(0, j);
            }
            if(str1.EndsWith(str2.Substring(0, j)))
            {
                return str2.Substring(0, j);
            }
        }
    }
    return string.Empty;
}

static void Main(string[] args)
{
    string str1 = "CGGCAGTGGTAGTCTGAG";
    string str2 = "TGAGCGCGCGCGCGCGCG";
    string result = GetMatchPart(str1, str2);
}
  • Related