Count Characters in String Java GUI AWT | How to Count Words
Here’s another small AWT program to count characters in String Java. The Java GUI Program also counts words. If you are coming here for the first time, just know that this chapter is a tributary of Java GUI AWT Classes in Java Chapter. You can go back and learn all the basics of AWT classes in Java.
The program here simply makes use of the length variable and method to retrieve the count in the form of integer value. We will be placing it in two separate labels titled ‘Words’ and ‘Characters’.
Count Words and Count Characters in String Java
Here’s the Java GUI program you came here looking for:
import java.awt.*; import java.net.*; import java.awt.event.*; public class LearnAWT extends Frame { TextArea ta; Label l1; Label l2; Button b; LearnAWT() { setTitle("Word Counter"); ta = new TextArea(); ta.setBounds(100, 100, 400, 400); b = new Button("Count"); b.setBounds(270,500,60,40); l1 = new Label(""); l1.setBounds(100, 50, 100, 30); l2 = new Label(""); l2.setBounds(250,50,100,30); add(b); add(ta); add(l1); add(l2); setLayout(null); setSize(600,600); setVisible(true); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { int s = ta.getText().split("\\s+").length; int c = ta.getText().length(); l1.setText("Words " + s); l2.setText("Characters " + c); } }); } public static void main(String []args) { new LearnAWT(); } }
As you can see in the above Java GUI program we have created two labels, a text area and a button. The Text Area will be the part where an end user is going to type stuff. The logic of the program, as usual, goes in the actionPerformed() method where we have simply grabbed the length of text area using length() method. It will be our Characters. We have also used the String’s split() method to separate each word based on their white spaces.
Here you need to remember what we have learnt in the Regex chapter about white spaces. If we would have used just “\\s” instead of “\\s+” it would have only taken care of instances in the first line.
On clicking the button in the program you will get the following result:
You can choose to count characters without the white spaces too like the data we get in a word file. Why don’t you figure that out yourself?
1 Response
[…] How to Count Characters and Word in a String […]