Skip to main content

String 类

创建 String

String s1 = "Runoob";              // String 直接创建
String s2 = "Runoob"; // String 直接创建
String s3 = s1; // 相同引用
String s4 = new String("Runoob"); // String 对象创建
String s5 = new String("Runoob"); // String 对象创建

或者这样:

public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

字符串长度

public class StringDemo {
public static void main(String args[]) {
String site = "Jetzihan.com";
int len = site.length();
System.out.println( "Jetzihan网址长度 : " + len );
}
}
res

Jetzihan网址长度 :12

连接字符串

String 类提供了连接两个字符串的方法:

string1.concat(string2);

返回 string2 连接 string1 的新字符串。也可以对字符串常量使用 concat() 方法,如:

public class StringDemo {
public static void main(String args[]) {
String string1 = "我的名字:";
System.out.println("1、" + string1 + "czh");
}
}
res

1、我的名字:czh

创建格式化字符串

我们知道输出格式化数字可以使用 printf() 和 format() 方法。

String 类使用静态方法 format() 返回一个String 对象而不是 PrintStream 对象。

String 类的静态方法 format() 能用来创建可复用的格式化字符串,而不仅仅是用于一次打印输出。

如下所示:

System.out.printf("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", floatVar, intVar, stringVar);

你也可以这样写:

String fs;
fs = String.format("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
" %s", floatVar, intVar, stringVar);

String API

菜鸟教程