Java 程序:计算字符串中字符频率
原文:https://www.studytonight.com/java-programs/java-program-to-find-the-frequency-of-character-in-string
在本教程中,我们将学习如何计算字符串中字符的频率。这意味着我们将计算字符串中哪个字符出现了多少次。
这可以通过先遍历字符串,然后计算字符出现的次数来实现。但是在进一步深入之前,如果你不熟悉字符串的概念,那么一定要查看 Java 中Strings的文章。
输入:输入字符串:今晚学习
输出:字符及其对应的频率:
字符=频率
S = 1
t = 2
u = 1
d = 1
y = 1
T = 1
o = 1
n = 1
i = 1
g = 1
h = 1
程序 1:计算字符串中字符的频率
在这个程序中,我们将看到当字符串在程序中被预定义时,如何计算字符串中字符的频率。
算法
开始
声明字符串
初始化它。
使用频率数组存储每个字符的频率。
将字符串转换为字符数组
使用两个 for 循环来计算每个元素的频率。
使用第一个 for 循环遍历数组的每个字符。
将频率数组的每个元素初始化为 1。
使用另一个 for 循环遍历剩余的字符。
检查元素的总出现次数。
如果元素再次出现,则增加频率数组中的值。
将字符数组设置为 0,以避免计算访问的字符。
打印字符及其对应的频率。
停下来。
下面是计算 Java 字符串中字符频率的 Java 代码。
/*Java Program to find the frequency of characters in a string*/
public class Main
{
public static void main(String[] args)
{
String str = "Study Tonight";
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 <str.length(); i++)
{
freq[i] = 1;
for(int j = i+1; j <str.length(); 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 <freq.length; i++)
{
if(str1[i] != ' ' && str1[i] != '0')
System.out.println(str1[i] + " " + freq[i]);
}
}
}
输入的字符串为今晚学习 字符串中字符的频率如下: 字符频率 S1 T2 u1 D1 y 1 T1 o 1 n1 I 1 G1 h 1
程序 2:计算字符串中字符的频率
在这个程序中,我们将看到当字符串是用户定义的时,如何计算字符串中字符的频率。这里,在这个程序中,我们将要求用户输入一个字符串,然后我们将计算字符串中字符的频率。
算法
开始
声明字符串
请用户初始化它。
使用频率数组存储每个字符的频率。
将字符串转换为字符数组
使用两个 for 循环来计算每个元素的频率。
使用第一个 for 循环遍历数组的每个字符。
将频率数组的每个元素初始化为 1。
使用另一个 for 循环遍历剩余的字符。
检查元素的总出现次数。
如果元素再次出现,则增加频率数组中的值。
将字符数组设置为 0,以避免计算访问的字符。
打印字符及其对应的频率。
停下来。
下面是计算 Java 字符串中字符频率的 Java 代码。
/*Java Program to find the frequency of characters in a string*/
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string is: ");
String str = sc.nextLine();
int[] freq = new int[str.length()]; //Frequency array to store the frequency of each character
//Convert the given string into character array
char str1[] = str.toCharArray();
for(int i = 0; i <str.length(); i++)
{
freq[i] = 1;
for(int j = i+1; j <str.length(); 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 <freq.length; i++)
{
if(str1[i] != ' ' && str1[i] != '0')
System.out.println(str1[i] + " " + freq[i]);
}
}
}
输入字符串为:字符频率计数 字符串中字符的频率如下: 字符频率 C2 h1 a2 r 3 C2 t 2 e 3 s 1 F 1 q 1 u 2 n 2 y 1 o 1