C# program to find the longest common prefix string amongst an array of strings
To find the longest common prefix string among an array of strings in C#, you can compare the characters of the strings at each position until a mismatch occurs. Here's an example program that finds the longest common prefix string:
using System;
public class Program {
public static void Main(string[] args) {
string[] strings = { "flower", "flow", "flight" };
string longestPrefix = FindLongestCommonPrefix(strings);
Console.WriteLine("Longest common prefix: " + longestPrefix);
}
public static string FindLongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) {
return "";
}
string prefix = strs[0];
for (int i = 1; i < strs.Length; i++) {
while (!strs[i].StartsWith(prefix)) {
prefix = prefix.Substring(0, prefix.Length - 1);
if (prefix.Length == 0) {
return "";
}
}
}
return prefix;
}
}
In this program, we have an array of strings called strings. We use the FindLongestCommonPrefix method to find the longest common prefix among the strings. The method starts by initializing the prefix variable with the first string in the array. It then compares the prefix with each subsequent string in the array using the StartsWith method. If the string does not start with the prefix, the prefix is gradually shortened by removing the last character until a match is found or the prefix becomes empty. Finally, the method returns the prefix as the longest common prefix.
The program outputs the longest common prefix:
Longest common prefix: fl
In this case, the longest common prefix among the strings "flower", "flow", and "flight" is "fl".