2009-08-07 5 views

Répondre

4

Pour trouver mots répétés vous pouvez diviser le texte par des espaces, le classer par ordre alphabétique et rechercher des instances répétées en effectuant une boucle sinle à travers le tableau de mots.

Les phrases répétées sont plus difficiles à détecter car vous devez essayer des combinaisons de mots, ce qui est très récurrent.

+0

Veillez à utiliser une expression régulière pour supprimer plusieurs espaces. –

+0

Je suggère de stocker ces mots avec l'index dans le texte pour un accès plus rapide – Scoregraphic

1

Pour correspondre les mots répétés dans une chaîne: (De http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx)

using System; 
using System.Text.RegularExpressions; 

public class Test 
{ 
    public static void Main() 
    { 

     // Define a regular expression for repeated words. 
     Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b", 
      RegexOptions.Compiled | RegexOptions.IgnoreCase); 

     // Define a test string.   
     string text = "The the quick brown fox fox jumped over the lazy dog dog."; 

     // Find matches. 
     MatchCollection matches = rx.Matches(text); 

     // Report the number of matches found. 
     Console.WriteLine("{0} matches found in:\n {1}", 
          matches.Count, 
          text); 

     // Report on each match. 
     foreach (Match match in matches) 
     { 
      GroupCollection groups = match.Groups; 
      Console.WriteLine("'{0}' repeated at positions {1} and {2}", 
           groups["word"].Value, 
           groups[0].Index, 
           groups[1].Index); 
     } 
    }  
} 

Pour changer la couleur d'un segment de texte dans un RichTextBox:

RichTextBox rtb = new RichTextBox(); 
rtb.SelectionStart = 4; 
rtb.SelectionLength = 7; 
rtb.SelectionColor = Color.Red; 
+1

+1, Très belle réponse détaillée! –

+0

correspond uniquement aux mots adjacents. ne trouvera pas le même mot dans toute la chaîne. –

0

Essayez ceci:

string value = "She sells sea shells by the sea shore"; 
Regex.Split(value, @"\W+").ToList() 
    .GroupBy(w => w) 
    .Where(w => w.Count() > 1) 
    .Select(w => w.Key).ToList() 
    .ForEach(w => Console.WriteLine("'{0}' repeats in the string", w)); 
Questions connexes