foreach
string str = "abcdaab"; //Solution 1 - remove the character, and compare its length. int result1 = str.Length - str.Replace("a", "").Length; //Solution 2 - split the string into an array using the character as a delimiter int result2 = str.Split('a').Length - 1; //Solution 3 - use the LINQ 'Count' extension method int result3 = str.ToCharArray().Count(c => c == 'a');
int count = 0; char charToCount = 'i'; foreach (char c in string123) { if( c == charToCount ) { count++; } }
string abc="1234567777"; int k = abc.Length;
string abc = "adkjddaadtyy"; int Count=0; foreach (char c in abc) { if (c == 'd') { Count++; } } int k = Count;
String s = "foo abc"; int count = 0; foreach (char c in s) { count++; }
Dictionary<string, int> characterCountList = new Dictionary<string, int>(); string word = "BaNAna"; word = word.ToLower(); bool check = false; foreach(var c in word) { var count = 0; foreach(var character2 in word) { if (!characterCountList.ContainsKey(c.ToString())) { check = true; if (character2 == c) { count++; } } else check = false; } if(check) characterCountList.Add(c.ToString(), count); } foreach(var data in characterCountList) Console.WriteLine(data.ToString());
O(N²)
O(N)
N²
Dictionary<char, int> characterCount = new Dictionary<char, int>(); foreach (char c in word) { char normalizedChar = char.ToUpper(c); characterCount.TryGetValue(normalizedChar, out int count); // If the key does not already exist, count will be initialized to 0 here. characterCount[normalizedChar] = count + 1; } foreach (KeyValuePair<char, int> pair in characterCount) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)