Count repetitive words in string array in C#
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//string[] _list = []; ;
List a = new List();
//bool inWord = false;
string[] arr = {"hello","test","hello","raf"};
int _counter = 0;
//int c = 0;
for (int i = 0; i

Emily FosterRank #3,495 · 415 reputationPosted Apr 12, 2025, 7:27 AM EDT
Certainly! The code you provided aims to count the occurrences of each word in the `arr` string array and display the count for each unique word. Let's break down how the code achieves this:
1. It initializes an empty list `a` to store unique words encountered.
2. The string array `arr` contains four words: "hello", "test", "hello", and "raf".
3. The `_counter` variable is used to keep track of the count of each word.
4. The `for` loop iterates over each word in the `arr` array.
5. For each word:
- If the word is already in the list `a`, `_counter` is incremented and the count is displayed.
- If the word is not in the list `a`, it is added to `a`, and the count is displayed.
However, there is a small issue in the code that resets the `_counter` to 0 in each iteration of the loop. This causes the count to always display as 1 for each word. To fix this, you should move the `_counter = 0;` line outside of the loop.
Here's the corrected loop part of the code:
for (int i = 0; i < arr.Length; i++) { if (a.Contains(arr[i])) { _counter++; } else { a.Add(arr[i]); } Console.WriteLine(arr[i] + " : " + _counter); }Now, the `_counter` will correctly accumulate the count of each word throughout the loop iterations, providing the desired outcome. This adjustment ensures that the count displayed represents the actual occurrence of each word in the array.