程序说明:
程序完成在窗口的一个JTextField中,输入一行字符串,按回车后,分离出的一组单词结果显示在窗口的JTextArea中。假设用一个空格字符作为单词之间的分隔符。
程序解析:
String类的单词解析方法为:String【】 split(String regex),其中regex中的内容可以是单词之间的分解符,可以是单个分解符,也可以是用“|”分割的多个分解符。如:
String a【】;
String s=“I love computer science”
a=s.split(" ");
则返回含有4个单词的字符串数组。而:
String s="Hello,I am a student"
a=s.split("|,");
表示单词之间的分隔符是空格或逗号,所以返回含有5个单词的字符串数组。
程序源代码如下:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class example extends JFrame{
private JLabel promptLabel;
private JTextField inputField;
private JTextArea outputArea;
public example(){
super("测试String的方法split");
Container container=getContentPane();
container.setLayout(new FlowLayout());
promptLabel=new JLabel("输出一个句子,然后回车");
container.add(promptLabel);
inputField=new JTextField(20);
inputField.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String input=e.getActionCommand();
String[]tokens=input.split(" ");
outputArea.setText("Number of elements:"+tokens.length+"\nThe tokens are:\n");
for(String token:tokens)
outputArea.append(token+"\n");
}
});
container.add(inputField);
outputArea=new JTextArea(10,20);
outputArea.setEditable(false);
container.add(new JScrollPane(outputArea));
setSize(275,240);
setVisible(true);
}
public static void main(String args[]){
example application=new example();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
程序运行结果如下