How to count character occurrence in a string? #198
-
I want to count char occurrence in a string by building a dictionary. dict: <character, occurence>. But I did not figure out how to build such dictionary; First try. public static class Test
{
public static void Main(string[] args)
{
Dictionary<string, int>() d;
string s = "abcda";
// what is the type of s[0]
d[s[0]] = 1;
}
} Fusion reports s[0] is not a string: test.fu(9): ERROR: Cannot convert '(-128 .. 65535)' to 'string' Second try. public static class Test
{
public static void Main(string[] args)
{
Dictionary<int, int>() d;
string s = "abcda";
// what is the type of s[0]
d[s[0]] = 1;
}
} to Java: // Generated automatically with "fut". Do not edit.
import java.util.HashMap;
public final class Test
{
private Test()
{
}
public static void main(String[] args)
{
final HashMap<Integer, Integer> d = new HashMap<Integer, Integer>();
String s = "abcda";
d.put(s.charAt(0), 1);
}
} The java code won't compile becuase mismatch of key type: char and Integer. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
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. |
Beta Was this translation helpful? Give feedback.
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:
but note that non-ASCII code points will differ from language to language.