Longest Common Prefix using Word by Word Matching | C # Program to find the longest common prefix ; A Utility Function to find the common prefix between strings - str1 and str2 ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; Driver Code
using System ; class GFG { static String commonPrefixUtil ( String str1 , String str2 ) { String result = " " ; int n1 = str1 . Length , n2 = str2 . Length ; for ( int i = 0 , j = 0 ; i <= n1 - 1 && j <= n2 - 1 ; i ++ , j ++ ) { if ( str1 [ i ] != str2 [ j ] ) { break ; } result += str1 [ i ] ; } return ( result ) ; } static String commonPrefix ( String [ ] arr , int n ) { String prefix = arr [ 0 ] ; for ( int i = 1 ; i <= n - 1 ; i ++ ) { prefix = commonPrefixUtil ( prefix , arr . GetValue ( i ) . ToString ( ) ) ; } return ( prefix ) ; } public static void Main ( ) { String [ ] arr = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = arr . Length ; String ans = commonPrefix ( arr , n ) ; if ( ans . Length > 0 ) { Console . Write ( " The ▁ longest ▁ common ▁ " + " prefix ▁ is ▁ - ▁ " + ans ) ; } else { Console . Write ( " There ▁ is ▁ no ▁ common ▁ prefix " ) ; } } }