Skip to content

How to count character occurrence in a string? #198

Answered by pfusik
academyofzhuang asked this question in Q&A
Discussion options

You must be logged in to vote

You should first decide what you mean by "character" and understand that different programming languages have different native string encodings. For instance, Java uses UTF-16.

You can count code points this way:

public static class Test
{
	public static void Main(string[] args)
	{
		Dictionary<int, int>() d;
		string s = "abcda";
		foreach (int c in s)
			d[c] = d.ContainsKey(c) ? d[c] + 1 : 1;
		foreach ((int c, int count) in d)
			Console.WriteLine($"Code point {c}: {count} occurrences");
	}
}

but note that non-ASCII code points will differ from language to language.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by academyofzhuang
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants