as example
string[ ] a = “a,b,c,d,a,a,c,e,f, b,b, b”;
how to check duplicated and show if have duplicated like this
a 3
b 4
c 2
thanks for everyone
as example
string[ ] a = “a,b,c,d,a,a,c,e,f, b,b, b”;
how to check duplicated and show if have duplicated like this
a 3
b 4
c 2
thanks for everyone
Ensure you are using System.Collections.Generic;
Dictionary<string, int> CountInstancesOfString (string[] arr) {
var result = new Dictionary<string, int>();
foreach(var str in arr) {
if (result.ContainsKey(str))
result[str]++;
else
result.Add(str, 0);
}
return result;
}
If you put that in C# that will just be one string. An array of strings would be more like
string[] stringarray = { "aa", "bb", "cc", "dd" };
For a list it would be more like
List<string> listStrings = new List<string>();
lstStrings.Add("aa");
lstStrings.Add("bb");
lstStrings.Add("cc");
lstStrings.Add("dd");
In other case you can run a for loop to iterate through the whole thing. Foreach can also work. How you do the counting depends on exactly what you want to do and what you mean by the same. It also depends on what you intend on doing with that information once you get it.
I’m a bit confused
Maybe i’m not so familiar with this
can you explain more details?
the string array is random generated
the array list and array string is ramdomly
Check the accepted answer here. You can modify it for your purposes.
Well, it’s pretty straight forward. This method takes an array of strings.
//so, arr would be {"aa","bb","aa","bb","aa"}, whatever.
Dictionary<string, int> CountInstancesOfString (string[] arr) {
//This is a dictionary that uses strings as keys and ints as values
var result = new Dictionary<string, int>();
//We loop through every item in the array.
foreach(var str in arr) {
//If the dictionary contains the string, it increments the value by one
if (result.ContainsKey(str))
result[str]++;
else
//Otherwise it creates it.
result.Add(str, 1);
}
//So, as in the above example, the result dictionary would hold:
//"aa" : 3
//"bb" : 2
return result;
}