13.7 修改字符串 因为字符串(String)对象是不可改变的,每当想修改一个字符串(String)时,就必须采用或者将它复制到StringBuffer或者使用下面字符串(String)方法中的一种,这些方法都将构造一个完成修改的字符串的拷贝。 13.7.1 substring( ) 利用substring( )方法可以截取子字符串,它有两种形式。其中第一种形式如下: String substring(int startIndex) 这里startIndex指定了子字符串开始的下标。这种形式返回一个从startIndex开始到调用字符串结束的子字符串的拷贝。substring( )方法的第二种形式允许指定子字符串的开始和结束下标: String substring(int startIndex, int endIndex) 这里startIndex指定开始下标,endIndex指定结束下标。返回的字符串包括从开始下标直到结束下标的所有字符,但不包括结束下标对应的字符。下面的程序使用substring( )方法完成在一个字符串内用一个子字符串替换另一个子字符串的所有实例的功能: // Substring replacement. class StringReplace { public static void main(String args[]) { String org = "This is a test. This is, too."; String search = "is"; String sub = "was"; String result = ""; int i; do { // replace all matching substrings System.out.println(org); i = org.indexOf(search); if(i != -1) { result = org.substring(0, i); result = result + sub; result = result + org.substring(i + search.length()); org = result; } } while(i != -1); } } 这个程序的输出如下所示: This is a test. This is, too. Thwas is a test. This is, too. Thwas was a test. This is, too. Thwas was a test. Thwas is, too. Thwas was a test. Thwas was, too. 13.7.2 concat( ) 使用concat( )可以连接两个字符串,一般形式如下: String concat(String str) 这个方法创建一个新的对象,该对象包含调用字符串。而str的内容跟在调用字符串的后面。concat( )方法与+运算符执行相同的功能。例如, String s1 = "one"; String s2 = s1.concat("two"); 将字符串“onetwo”赋给s2。它和下面的程序段产生相同的结果: String s1 = "one"; String s2 = s1 + "two"; 13.7.3 replace( ) replace( )方法用另一个字符代替调用字符串中一个字符的所有具体值。它具有如下的一般形式: String replace(char original, char replacement) 这里original指定被由replacement指定的字符所代替的字符,返回得到的字符串。例如: String s = "Hello".replace('l', 'w'); 将字符串“Hewwo”赋给s。 13.7.4 trim( ) trim( )方法返回一个调用字符串的拷贝,该字符串是将位于调用字符串前面和后面的空白符删除后的剩余部分。它的一般形式如下: String trim( ) 这里是一个例子: String s = " Hello World ".trim(); 将字符串“Hello World”赋给s。 trim( )方法在处理用户输入的命令时,是十分有用的。例如,下面的程序提示用户输入一个州名后显示该州的首府名。程序中使用trim( )方法删除在用户输入期间,不经意间输入的任何前缀或后缀空白符。 // Using trim() to process commands. import java.io.*; class UseTrim { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter 'stop' to quit."); System.out.println("Enter State: "); do { str = br.readLine(); str = str.trim(); // remove whitespace if(str.equals("Illinois")) System.out.println("Capital is Springfield."); else if(str.equals("Missouri")) System.out.println("Capital is Jefferson City."); else if(str.equals("California")) System.out.println("Capital is Sacramento."); else if(str.equals("Washington")) System.out.println("Capital is Olympia."); // ... } while(!str.equals("stop")); } }
<<上一页
1
2
3
4
5
6
7
8
9
10
11
12
下一页>>
|