There is a text -

cat cat cat cat cat cat cat cat cat cat dog dog dog dog dog 

I make an array of text from text using Text.Split(' ') . How then using the foreach loop to get such a text? -

 cat_10 dog_5 

If the word is found once in a row - you need to do cat_1

  • and if the text is in one copy? - EvgeniyZ
  • @EvgeniyZ corrected - Stepan

2 answers 2

Well, you can try this:

 string text = "cat cat cat cat cat cat cat cat cat cat dog dog dog dog dog"; var result = text.Split().GroupBy(x => x).Select(group=> $"{group.Key}_{group.Count()}"); var resultString = string.Join(" ", result); 
  1. We break through Split.
  2. Grouped by value.
  3. Key_count transform into the IEnumerable<string> collection, where each value will be of the form Key_count .
  4. Use string.Join convert the collection to a string.
    * This item can be replaced by adding after select() something like .Aggregate((current, next) => current + " " + next) . Then you will immediately receive the string you need.

If for some reason you don’t want to use LINQ and all new C # freaks, then do something like the following:

 string text = "cat cat cat cat cat cat cat cat cat cat dog dog dog dog dog"; string[] arr = text.Split(); string result = ""; foreach (var val in arr) { if (!result.Contains(val)) { int count = 0; for (var i = 0; i < arr.Length; i++) { if (arr[i] == val) count++; } result += val + "_" + count + " "; } } 

For speed, you can use StringBuilder , and all loops on for .

Result:

 cat_10 dog_5 

    With regular season:

     string text = "wolf cat cat cat cat cat cat cat cat cat cat dog dog dog dog dog"; Regex r = new Regex(@"((\w+)( \2)*)"); string result = r.Replace(text, m => m.Groups[2].Value + "_" + m.Value.Split().Length); 

    Result:

     wolf_1 cat_10 dog_5