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);
- We break through Split.
- Grouped by value.
Key_count transform into the IEnumerable<string> collection, where each value will be of the form Key_count .- 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