Java String类
字符串在Java编程中广泛使用,字符串就是一系列字符(由一个个的字符组成)。 在Java编程语言中,字符串被视为对象。 Java平台提供String类来创建和操作字符串。 1. 创建字符串创建字符串的最直接方法是 - String str = "Hello world!"; 每当它在代码中遇到字符串文字时,编译器就会创建一个String对象,在本例中str对象的值为Hello world!。 与其他对象一样,可以使用new关键字和构造函数来创建String对象。String类有11个构造函数,方便使用不同的源(例如:字符数组)提供字符串的初始值。 示例 public class StringDemo { public static void main(String args[]) { char[] helloArray = { 'Y', 'i', 'i', 'b', 'a', 'i' }; String helloString = new String(helloArray); System.out.println( helloString ); } } 执行上面示例代码,得到下结果: Yiibai 注 - String类是不可变的,因此一旦创建,就无法更改String对象。 如果想要对字符串进行大量修改,则应使用StringBuffer和StringBuilder。 2. 字符串长度用于获取对象信息的方法称为访问器方法。 可以与字符串一起使用来获取字符串长度的一个访问器方法是length()方法,它返回字符串对象中包含的字符数。 以下程序是String类的length()方法的示例。 public class StringDemo { public static void main(String args[]) { String greeting = "Hi,Welcome to Yiibai.com"; int len = greeting.length(); System.out.println( greeting+" 字符串的长度是: " + len ); } } 执行上面示例代码,得到下结果: Hi,Welcome to Yiibai.com 字符串的长度是: 24 3. 连接字符串String类包含一个用于连接两个字符串的方法 - string1.con
字符串在Java编程中广泛使用,字符串就是一系列字符(由一个个的字符组成)。 在Java编程语言中,字符串被视为对象。
Java平台提供String类来创建和操作字符串。
1. 创建字符串
创建字符串的最直接方法是 -
String str = "Hello world!";
每当它在代码中遇到字符串文字时,编译器就会创建一个String对象,在本例中str对象的值为Hello world!。
与其他对象一样,可以使用new关键字和构造函数来创建String对象。String类有11个构造函数,方便使用不同的源(例如:字符数组)提供字符串的初始值。
示例
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'Y', 'i', 'i', 'b', 'a', 'i' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
执行上面示例代码,得到下结果:
Yiibai
注 -
String类是不可变的,因此一旦创建,就无法更改String对象。 如果想要对字符串进行大量修改,则应使用StringBuffer和StringBuilder。
2. 字符串长度
用于获取对象信息的方法称为访问器方法。 可以与字符串一起使用来获取字符串长度的一个访问器方法是length()方法,它返回字符串对象中包含的字符数。
以下程序是String类的length()方法的示例。
public class StringDemo {
public static void main(String args[]) {
String greeting = "Hi,Welcome to Yiibai.com";
int len = greeting.length();
System.out.println( greeting+" 字符串的长度是: " + len );
}
}
执行上面示例代码,得到下结果:
Hi,Welcome to Yiibai.com 字符串的长度是: 24
3. 连接字符串
String类包含一个用于连接两个字符串的方法 -
string1.concat(string2);
这将返回一个新字符串:string1,并且string1在结尾处添加了string2。 还可以将concat()方法与字符串文字一起使用,例如 -
"My name is ".concat("Maxsu");
字符串通常使用+运算符连接,如 -
"Hello," + " world" + "!"
上面代码执行后得到的结果是:
"Hello, world!"
下面再来看另一个例子 -
public class StringDemo {
public static void main(String args[]) {
String string1 = "Bai";
System.out.println("Yii" + string1 + ".com");
}
}
上面代码执行后得到的结果是:
YiiBai.com
3. 创建格式化字符串
Java中使用printf()和format()方法来打印带有格式化数字的输出。 String类有一个等效的类方法format(),它返回一个String对象而不是一个PrintStream对象。
使用String的static 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);
4. String类方法
以下是String类定义的方法列表 -
交流与评论