代码改变世界

Java 字符串剪切

2012-10-26 00:53  coffeescript  阅读(962)  评论(0)    收藏  举报

String类在处理字符串时用的比较多的是这两个方法:

1.substring(int beginIndex)    截取从beiginIndex为开始到字符串尾的子字符串

  String s="unhappy";  s.substring(2)的结果为"happy"

2.substring(int beginIndex,int endIndex)    截取从beiginIndex开始到endIndex-1结束的子字符串,字符串长度为endIndex-beginIndex

  String s="hamburger";  s.substring(4,8)的结果为"urge"

 

在TextArea或JTextArea中做剪切或者黏贴时,可以使用TextArea或JTextArea类的getSelectionStart()和getSelectionEnd()等方法实现。

以JTextArea为例

JTextArea ta=new JTextArea();
String str=ta.getText();
str=str.substring(0,ta.getSelectionStart())+str.substring(ta.getSelectionEnd);
ta.setText(str)

黏贴也是一样,只不过要加上temp值。

其实JTextArea类本身继承了父类的copy(),cut(),paste()方法,可以直接拿来使用。