gpt4 book ai didi

java - 计算字符串中字符的出现次数(频率)

转载 作者:行者123 更新时间:2023-12-02 13:00:31 28 4
gpt4 key购买 nike

我有一个 GUI,可以计算字符串中第一个字母的出现次数。我希望它以列格式计算所有字母,例如:

enter image description here

这是我到目前为止所拥有的:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class Index2 extends JFrame implements ActionListener
{
private JTabbedPane jtabbedPane;
private JPanel characterFinder;
JTextField enterText, countText;

public Index2()
{
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Total Characters");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createCharacterFinder();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Count Characters", characterFinder);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
public void createCharacterFinder()
{
characterFinder = new JPanel();
characterFinder.setLayout(null);
JLabel enterLabel = new JLabel(
"Enter Some Text");
enterLabel.setBounds(90, 5, 260, 20);
characterFinder.add(enterLabel);
enterText = new JTextField();
enterText.setBounds(10, 30, 270, 70);
characterFinder.add(enterText);

JButton search = new JButton("Count Occurences of Each Letter");
search.setBounds(15, 100, 260, 20);
search.addActionListener(this);
characterFinder.add(search);

countText = new JTextField();
countText.setBounds(80, 130, 120, 500);
characterFinder.add(countText);
}
public void actionPerformed(ActionEvent e){
String st=enterText.getText();
char searchedChar=enterText.getText().charAt(0);
count(searchedChar,st);
}
public int count(char c, String str) {
if (str == null) return 0;
int cnt = 0;
for (int i = 0;; cnt++) {
if ((i = str.indexOf(c,i)+1) == 0) break;
}
countText.setText("Character "+c+" occurs "+cnt+" times");
return cnt;
}

public static void main(String[] args)
{
JFrame frame = new Index2();
frame.setSize(300, 700);
frame.setVisible(true);
}
}

最佳答案

计算字符(假设 ASCII 字符)的一个好方法是利用 'a' 可以直接映射到数字的事实。

int[] charCounts(String s) {
int[] counts = new int[256]; // maximum value of an ASCII character
char[] c = s.toCharArray();
for (int i=0;i<c.length;++i) {
counts[c[i]]++;
}
return counts;
}

现在要查找任何特定元素的计数,您可以执行 counts['a']

使用上面这样的方法预先进行计数,然后使用非常粗略的方式显示计数,可能会使代码更加整洁:

int[] counts = charCounts("my string");
StringBuilder sb = new StringBuilder();
for (char a = 'a'; a <= 'z'; a++) {
sb.append(a).append(" occurred ").append(counts[a]).append(" times\n");
}

关于java - 计算字符串中字符的出现次数(频率),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5539476/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com