Slip No.10
A) Write a java program to count the frequency of each character in a given string.1. Open Notepad.
2. Type the following code:
-
public class Main
{
public static void main(String[] args)
{
String str = "Hello Students";
int[] freq = new int[str.length()];
System.out.println("The entered string is "+str);
//Convert the given string into character array
char str1[] = str.toCharArray();
for(int i = 0; i
freq[i] = 1;
for(int j = i+1; j
if(str1[i] == str1[j])
{
freq[i]++;
//Set str1[j] to 0 to avoid printing visited character
str1[j] = '0';
}
}
}
//Displays the characters and their corresponding frequency
System.out.println("Frequencies of the characters in the string are as below: ");
System.out.println("Characters frequencies");
for(int i = 0; i
if(str1[i] != ' ' && str1[i] != '0')
System.out.println(str1[i] + " " + freq[i]);
}
}
}
4. Open the Command Prompt.
5. Compile the Java program by typing:
javac Main.java
6. Run the compiled Java program by typing:
java Main
No comments:
Post a Comment