How to count frequency of characters in a string?
You can use a java Map and map a char
to an int
. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.
For example:
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
Integer val = map.get(c);
if (val != null) {
map.put(c, new Integer(val + 1));
}
else {
map.put(c, 1);
}
}
At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.
Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.
Count the number of occurrences of a character in a string
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring
sub
in the range[start, end]
. Optional argumentsstart
andend
are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
Counting frequency of characters in a string using JavaScript
Here you go:
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
Calculate the frequency of characters in a string (Java, Performance)
You don't need to explicitly initialize 26 entries in your frequency array (the default value is zero); you also don't need to keep the table of characters (it is sufficient to know the offset). That is, your code can eliminate c
entirely and calculate each letter; like,
Scanner sc = new Scanner(System.in);
int[] f = new int[26];
System.out.println("Enter a string.");
String orig = sc.nextLine();
String k = orig.trim().toUpperCase();
System.out.println("Checking string = " + orig);
for (char ch : k.toCharArray()) {
f[ch - 'A']++;
}
System.out.println("Char\tFreq");
for (int i = 0; i < f.length; i++) {
if (f[i] != 0) {
System.out.println((char) ('A' + i) + "\t" + f[i]);
}
}
Counting Character Frequency in String(Java)
Well, count
is an int[]
with 256 slots:
int count[] = new int[MAX_CHAR]; // MAX_CHAR is 256
Your algorithm defines MAX_CHAR = 256
, because it assumes the string consists only of 8-Bit ASCII characters.
[0, 0, ..., 0, 0] // 256 slots
Now you're iterating each character in string str
and cast it to an integer (see type casting of primitives in Java). An A
will be casted to 65 (ASCII table), a B
to 66 and so on. The casted int
is the slot to increment. So a string A
would lead to an increment of the integer at index 65. Your question was primarily about
count[str.charAt(i)]++
That translates to this:
char c = str.charAt(i); // c = A
int index = c; // c = A, casted to an int = 65
count[index]++ // increments the int at position 65
Result:
[0, 0, ..., 1, ..., 0, 0]
^ index 65
The next A
would increment the int at index 65 again:
[0, 0, ..., 2, ..., 0, 0]
^ index 65
count the frequency of each character using the dictionary in python
You can iterate over string and update the dictionary accordingly and also there's no need of any count variable.
test_str = input().lower()
dicx = {}
for i in test_str:
if i in dicx:
dicx[i] += 1
else:
dicx[i] = 1
print(dicx)
Counting frequency of characters in a string using JavaScript
Here you go:
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
Related Topics
How to Have 2 Jvms Talk to One Another
How to Pass a Primitive Data Type by Reference
When Should I Use File.Separator and When File.Pathseparator
Spring Data JPA - How to Combine Multiple and and or Through Method Name
Warning - Build Path Specifies Execution Environment J2Se-1.4
Java: Detect Duplicates in Arraylist
Expression Language in Jsp Not Working
Eclipse Returns Error Message "Java Was Started But Returned Exit Code = 1"
Class Has Been Compiled by a More Recent Version of the Java Environment
How to Run Testng from Command Line
Sandbox Against Malicious Code in a Java Application
Using Generics in Spring Data JPA Repositories
Why Equals() Method When We Have == Operator
How to Create Immutable Objects in Java