【Java系列】String类的常用方法

String是Java中最常见的类。在开发中经常会用到String类相关的构造方法以及对象方法。下面进行一个简单的总结。

String对象的构造方法

直接使用字符串构造

最常用的构造方法,一般使用此构造方法。只要构造的字符串对象的内容一致,即使变量不同,其引用(地址)仍相同。

String str0 = "";
String str1 = "hello world !";
String str2 = "hello world !";
System.out.println(str0);
System.out.println(str1 == str2);

//result
//(空字符串,不显示)
//ture

public String()

构造空字符串对象。由于空字符串对象内容皆为空,因此其引用(地址)也相同。

String str1 = new String();
String str2 = new String();
System.out.println(str1 == str2);

//result
//false

public String​(String original)

构造非空字符串对象,是一种较为常见的构造方法。即使构造的字符串对象的内容一致,不同的变量的引用(地址)不同。

String str1 = new String("hello world !");
String str2 = "hello world !";
String str3 = new String("hello world !");
System.out.println(str1 == str2);
System.out.println(str1 == str3);

//result
//false
//false

public String​(char[] value)

使用字符数组构造字符串。

char[] value = new char[]{'a','b','c','1','2','3'};
String str = new String(value);
System.out.println(str);

//result
//abc123

public String​(char[] value, int offset, int count)

使用字符数组构造字符串。offset为偏移量,即开始字符的位置。
count为构造字符串的字符个数,从零开始计数,获取开始和结束位置的字符。

char[] value = new char[]{'a','b','c','1','2','3'};
String str = new String(value, 3, 2);
System.out.println(str);

//result
//12

String的动态方法(对象方法)

获取字符(数组)

public char[] toCharArray()

将字符串整体转换为字符数组。

String str = new String("hello world !");
char[] value = str.toCharArray();
System.out.println(value);
System.out.println(value[0]);

//result
//hello world !
//h

public char charAt​(int index)

从字符串中获取字符。charAt​方法将字符串打散后放入字符类型的数组中。
index为该数组的下标,从零开始计数。如果没有特殊情况,以下的下标都从0开始计数。

String str = new String("hello world !");
char char1 = str.charAt(4);
System.out.println(char1);

//result
//o

注意:该方法常用于获取中文字符。

String str = new String("你好世界!");
char char1 = str.charAt(2);
System.out.println(char1);

//result
//世

获取字节数组

public byte[] getBytes()

将已有的字符串整体转换为数组。

String str = new String("hello world !");
byte[] value = str.getBytes();
System.out.println(value[0]);
System.out.println(value[1]);

//result
//104
//101

public byte[] getBytes​(String charsetName) throws UnsupportedEncodingException

使用指定的字符集将此String编码为字节序列,将结果存储到新的字节数组中。
常用的字符集有(按使用频率递减):UTF-8,UTF-16,US-ASCII,ISO-8859-1。

import java.io.UnsupportedEncodingException;

public class Test {
    public static void main(String []args) {
        try{
            String str = new String("hello world !");
            byte[] value = str.getBytes("UTF-8");
            System.out.println(value[0]);
            System.out.println(value[1]);
        } catch(UnsupportedEncodingException e){
            System.out.println("Unsupported character set" + e);
        }
    }
}

//result
//104
//101

字符串比较

public boolean equals​(Object anObject)

将此String与另一个String进行比较,内容相同则结果为true,其余都为false。

String str1 = "hello world !";
System.out.println(str1.equals("hello world !"));

String str2 = "hello world !";
System.out.println(str2.equals(""));

//result
//true
//false

public boolean equalsIgnoreCase​(String anotherString)

将此String与另一个String比较,忽略大小写。其余与equals一致。

String str1 = "hello world !";
System.out.println(str1.equalsIgnoreCase("HeLLo World !"));

//result
//true

public int compareTo​(String anotherString)

按字典顺序(从右向左)比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的差值;
如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束。
如果参数字符串等于此字符串,则返回值 0;
如果此字符串小于字符串参数,则返回一个小于 0 的值;
如果此字符串大于字符串参数,则返回一个大于 0 的值。

String str1 = "hello world !";
String str2 = "hello world !";
String str3 = "hello world !!!";
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str3.compareTo(str1));

//result
//0
//-2
//2

public int compareToIgnoreCase​(String str)

除比较时不区分大小写外,比较过程与compareTo一致。

String str1 = "hello world !";
String str2 = "Hello WorLD !";
String str3 = "Hello WORld !!!";
System.out.println(str1.compareToIgnoreCase(str2));    //0
System.out.println(str1.compareToIgnoreCase(str3));    //-2
System.out.println(str3.compareToIgnoreCase(str1));    //2

字符串的查找

public boolean contains​(CharSequence s)

当且仅当此字符串包含指定的char值序列时,才返回true,其余结返回false。

String str1 = "hello world !";
System.out.println(str1.contains("h"));       //true
System.out.println(str1.contains("hello"));   //true
System.out.println(str1.contains("a"));       //false

public int indexOf​(String str)

返回指定子字符串第一次出现的字符串中的索引。如果没有出现则返回-1。

String str1 = "hello world !";
System.out.println(str1.indexOf​("w"));       //6
System.out.println(str1.indexOf​("hello"));   //0
System.out.println(str1.indexOf​("a"));       //-1

public int indexOf​(String str, int fromIndex)

从指定的索引处开始,返回指定子字符串第一次出现的字符串中的索引。如果没有出现则返回-1。
注意这里返回的索引是指“原字符串的索引”,而不是“从指定的索引处开始的字符串的索引”。

String str1 = "hello world !";
System.out.println(str1.indexOf​("w", 3));       //6
System.out.println(str1.indexOf​("hello", 3));   //-1
System.out.println(str1.indexOf​("a", 3));       //-1

public int lastIndexOf​(String str)

返回指定子字符串最后一次出现的字符串中的索引。如果子字符串为“”,则返回该字符串的长度。

String str = "hello world !";
System.out.println(str.lastIndexOf("o"));   //7
System.out.println(str.lastIndexOf("a"));   //-1
System.out.println(str.lastIndexOf(""));    //13

public int lastIndexOf​(String str, int fromIndex)

返回指定子字符串最后一次出现的字符串中的索引,从字符串的开始寻找到指定字符串索引为止。
如果此字符串中没有这样的字符,则返回 -1。

String str = "hello world !";
System.out.println(str.lastIndexOf("o",6));   //4
System.out.println(str.lastIndexOf("a",3));   //-1
System.out.println(str.lastIndexOf("",3));    //3

public boolean startsWith​(String str)

测试此字符串是否以指定的前缀开头,是则返回true。

String str = "hello world !";
System.out.println(str.startsWith("hello"));   //true
System.out.println(str.startsWith("world"));   //false

public boolean startsWith​(String prefix, int toffset)

测试从指定索引开始的此字符串的子字符串是否以指定的前缀开头,是则返回true。

String str = "hello world !";
System.out.println(str.startsWith("hello",2));   //false
System.out.println(str.startsWith("world",6));   //true

public boolean endsWith​(String suffix)

String str = "hello world !";
System.out.println(str.endsWith("hello"));   //false
System.out.println(str.endsWith("d !"));     //true

字符串的替换

public String replaceAll​(String regex, String replacement)

使用给定的参数 replacement 替换字符串所有匹配正则表达式 regex 的子字符串。

String str = "hello world !";
System.out.println(str.replaceAll("l","L"));         //heLLo worLd !
System.out.println(str.replaceAll("world","Java"));  //hello Java !

public String replaceFirst​(String regex, String replacement)

使用给定的参数 replacement 替换字符串中“首个”匹配的正则表达式 regex 的子字符串。

String str = "hello world !";
System.out.println(str.replaceFirst("l","L"));         //heLlo world !
System.out.println(str.replaceFirst("world","Java"));  //hello Java !

字符串拆分

public String[] split​(String regex)

根据匹配给定的正则表达式来拆分字符串。

String str = "hello world !";
String[] array = str.split("o");
for (String value : array){
    System.out.print(value + ",");
}

//result
//hell, w,rld !,

public String[] split​(String regex, int limit)

根据匹配给定的正则表达式以及拆分后的份数来拆分字符串。

String str = "hello world !";
String[] array = str.split("o",2);    //拆成两份
for (String value : array){
    System.out.print(value + ",");
}

//result
//hell, world !,

其他动态方法

public String concat(String str)

连接两个字符串。同常使用“+”来实现,因此此方法不常用。

String str = "hello";
System.out.println(str.concat(" world").concat(" !"));    //hello world !

public String intern()

返回字符串对象的规范化表示形式。
当调用 intern 方法时,如果常量池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object) 方法确定),则返回池中的字符串对象的引用。否则,将此 String 对象添加到池中,并且返回此 String 对象的引用。

String str1 = "hello world !";
String str2 = new String("hello world !");
String str3 = str2.intern();
System.out.println(str1 == str2);    //false
System.out.println(str1 == str3);    //true

public boolean isEmpty()

判断该字符串是否为空。为空则返回true。

String str1 = "hello";
String str2 = "";
System.out.println(str1.isEmpty());    //false
System.out.println(str2.isEmpty());    //true

public int length()

获取该字符串长度。

String str1 = "hello";
String str2 = "";
System.out.println(str1.length());    //5
System.out.println(str2.length());    //0

public String trim()

删除字符串的头尾空白符。

String str1 = "     hello      ";
System.out.println(str1.trim());    //hello

public String toUpperCase()

将此 String 中的所有的小写字符都转换为大写。非小写字母则不受到影响。

String str1 = "hello world !";
System.out.println(str1.toUpperCase());    //HELLO WORLD !

public String toLowerCase()

将此 String 中的所有大写字符都转换为小写。非大写英语字母则不受到影响。

String str1 = "HELLO WORLD !";
System.out.println(str1.toLowerCase());    //hello world !

String的静态方法(类方法)

字符串格式化

public static String format(String format, Object… args)

String str = String.format("year:%d, month:%d, date:%d, temperature:%4.2fC, weather:%s", 2020, 05, 15, 23.03, "sunny");
System.out.println(str);
//year:2020, month:5, date:15, temperature:23.03C, weather:sunny

参考

Class String
クラス Charset
Java compareTo() 方法

Add a Comment

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Close Bitnami banner