String - count the frequency of characters in a string Given a string S, count the frequency of characters in the string S (the occurrences of a character present in the string) Input: hello world where: First-line represents the input string Output: d 1 e 1 h 1 l 3 o 2 r 1 w 1 Explanation: Print the count of each distinct letter present in string S. Assumptions: String contains only lower case letters Length of string S can be 0 to 10000
时间: 2023-11-27 07:51:14 浏览: 65
Here's a sample code in Java that takes in a string input and outputs the frequency of characters in the string:
```java
import java.util.*;
public class FrequencyCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
int[] freq = new int[26]; // assuming only lower case letters
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
freq[c - 'a']++; // increment the frequency of the character
}
// print the frequency of each character
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
System.out.println((char) ('a' + i) + " " + freq[i]);
}
}
}
}
```
Sample input/output:
```
Enter a string: hello world
d 1
e 1
h 1
l 3
o 2
r 1
w 1
```
阅读全文