Java String类
Java中,字符串属于对象。
Java提供了String类来创建和操作字符串。
创建字符串
创建字符串最简单方式:
String str = "Hello World!"
使用关键字和构造方法来创建String对象。
String类有11种构造方法,这些方法提供不同的参数来初始化字符串,比如提供一个字符数组参数:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString )
运行结果如下:
hello.
注意:String类是不可改变的,一旦创建了String对象,那它的值就无法改变了。如果需要对字符串做很多修改,那么应该选择使用StringBuffer & StringBuilder类。
字符串长度
用于获取有关对象的信息的方法称为访问器方法。
String类的的一个访问器方法是length()方法,它返回字符串对象包含的字符数。
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
运行结果为:
String Length is :17
连接字符串
String 类提供了连接两个字符串的方法:
string.concat(string2);
返回string2连接string1的新字符串。
也可对字符串常量使用concat()方法,如:
“my name is ”.concat("Alary");
更常用的是使用 ‘+’ 操作符来连接字符串,如:
"hello," + "world" + "!";
运行结果为:
hello,world!
创建格式化字符串
输出格式化数字可以使用printf()和format(0方法。
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);