这篇Java教程基于JDK1.8。教程中的示例和实践不会使用未来发行版中的优化建议。
字符串
Java平台提供 String 类来创建并操作字符串。
创建字符串
创建字符串最直接的方式是:
String greeting = "Hello world!";
本例中,"Hello world!"是字符串文字—代码中被双引号括起来的字符序列。无论什么时候在代码中遇到字符串文字,编译器都会为该字符串创建一个对象—本例是指Hello world!。
和其他对象一样,你也可以使用new关键字和构造器来创建String对象。String 类提供了13个构造器,允许你提供不同来源的字符串初始值,比如字符的数组:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);
代码片段的最后一行代码将打印hello.
字符串长度
用于获取对象信息的方法称为访问器方法。和字符串相关的访问器方法有一个length() 方法,返回字符串对象中字符的长度。下面两行代码执行过后,len 等于17:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
回文是一个对称的单词或句子—它向前和向后拼写内容是相同的,忽略大小写和标点符号。这里有个反转回文字符串的示例程序。它调用了String类的方法CharAt(i),返回字符串中位置为 ith 的字符,从0开始计算。
public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
// put original string in an
// array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}
// reverse array of chars
for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}
String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}
程序运行后输出
doT saw I was toD
为完成反转,程序必须将字符串转换为字符数组,反转该数组得到另外一个数组,然后再把字符数组转换成字符串。String 类有一个方法,getChars() 能够将字符串转换成字符数组,这样就可以代替前面的for循环:
palindrome.getChars(0, len, tempCharArray, 0);
字符串拼接
String 类 包括一个方法来拼接2个字符串:
string1.concat(string2);
这将返回一个新字符串,string2将追加到string1的末尾。
*concat()*方法也可以用在字符串文字上,比如:
"My name is ".concat("Rumplestiltskin");
字符串更常见的拼接方式是使用“+”操作符,比如:
"Hello," + " world" + "!"
结果为:
"Hello, world!"
在print 语句中广泛使用*+*操作符。例如:
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
打印:
Dot saw I was Tod
这种拼接可以是任何对象的混合。对任何不是String 类型的对象,会调用它的toString() 方法将它转换为String 类型。
创建格式化的字符串
之前使用printf() 和 format() 方法来格式化数值。String 类有一个等价的方法:format() ,返回了String 对象而不是 PrintStream 对象。
使用String的静态*format()*方法让你创建可重用的格式化字符串,而不是一次性的打印语句。如下例:
System.out.printf("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
"and the string is %s",
floatVar, intVar, stringVar);
还可以这样来写:
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);