Java - String类

163 阅读1分钟

String 类

在Java语言中,提供了String类可以用来实例化字符串对象。
任何字符序列可以使用toString()来转化为String对象。

String string = "Hello World!";

String类示例

String类提供了很多种不同的构造方法,用来构造字符串对象,如下示例是其中的一种:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println(helloString);

String类是一个不可改变的类型,其实例化一旦生成,实例化对象则不可被改变。

1. length()

使用访问器方法length()来计算String对象的字符串长度。

String palindrome = "Dot saw I was Tod";
int len = palindrome.length();

2. charAt(i)

String对象中的第i个字符:

String palindrome = "Dot saw I was Tod";
System.out.println(palindrome.charAt(0));

3. 字符序列连接

// 1. concat(), string1和string2连接生成一个新的String对象
String new_string = string1.concat(string2); 

// 2. concat(), 普通的字符序列和string连接,生成一个新的String对象
"My name is ".concat("Rumplestiltskin");

// 3. + 号连接的字符序列
"Hello," + " world" + "!"

4. 创建格式化字符串

使用String类的format()静态方法来创建格式化的字符串:

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);