Longest Common Substring in an Array of Strings | C # program to find the stem of given list of words ; function to find the stem ( longest common substring ) from the string array ; Determine size of the array ; Take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; Check if the generated stem is common to all words ; If current substring is present in all strings and its length is greater than current result ; Driver Code ; Function call
using System ; using System . Collections . Generic ; class stem { public static String findstem ( String [ ] arr ) { int n = arr . Length ; String s = arr [ 0 ] ; int len = s . Length ; String res = " " ; for ( int i = 0 ; i < len ; i ++ ) { for ( int j = i + 1 ; j <= len ; j ++ ) { String stem = s . Substring ( i , j - i ) ; int k = 1 ; for ( k = 1 ; k < n ; k ++ ) if ( ! arr [ k ] . Contains ( stem ) ) break ; if ( k == n && res . Length < stem . Length ) res = stem ; } } return res ; } public static void Main ( String [ ] args ) { String [ ] arr = { " grace " , " graceful " , " disgraceful " , " gracefully " } ; String stems = findstem ( arr ) ; Console . WriteLine ( stems ) ; } }