1 public static void main(String[] args)
2 {
3 //return the number of words in a string
4
5 String example = "This is a good exercise";
6
7 int length = example.split(" ").length;
8
9 System.out.println("The string is " + length + " words long.");
10
11
12 }
1public class Frequency
2{
3 public static void main(String[] args) {
4 String str = "picture perfect";
5 int[] freq = new int[str.length()];
6 int i, j;
7
8 //Converts given string into character array
9 char string[] = str.toCharArray();
10
11 for(i = 0; i <str.length(); i++) {
12 freq[i] = 1;
13 for(j = i+1; j <str.length(); j++) {
14 if(string[i] == string[j]) {
15 freq[i]++;
16 //Set string[j] to 0 to avoid printing visited character
17 string[j] = '0';
18 }
19 }
20 }
21 //Displays the each character and their corresponding frequency
22 System.out.println("Characters and their corresponding frequencies");
23 for(i = 0; i <freq.length; i++) {
24 if(string[i] != ' ' && string[i] != '0')
25 System.out.println(string[i] + "-" + freq[i]);
26 }
27 }
28}
1 String name = "Carmen is a fantastic play"; //arbitrary sentence
2
3 int numWords = (name.split("\\s+")).length; //split string based on whitespace
4 //split returns array - find legth of array
5
6 System.out.println(numWords);
1 String str = "I am happy and why not
2 and why are you not happy and you should be";
3 String [] arr = str.split(" ");
4 Map<String, Integer> map = new HashMap<>();
5
6 for (int i=0 ; i < arr.length ; i++){
7 if (!map.containsKey(arr[i])){
8 map.put(arr[i],1);
9 } else{
10 map.put(arr[i],map.get(arr[i])+1);
11 }
12 }
13 for(Map.Entry<String, Integer> each : map.entrySet()){
14
15 System.out.println(each.getKey()+" occures " + each.getValue() + " times");
16 }