【Java】String类

String

public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence

字符串不变; 它们的值在创建后不能被更改。 字符串缓冲区支持可变字符串。 因为String对象是不可变的,它们可以被共享。 例如:

String str = "abc";

相当于:

char data[] = {'a', 'b', 'c'};
String str = new String(data);

String类包括用于检查序列的各个字符的方法,用于比较字符串,搜索字符串,提取子字符串以及创建将所有字符翻译为大写或小写的字符串的副本。

创建字符串

public class String_Test3 {

	public static void main(String[] args) throws UnsupportedEncodingException {
		//1.定义常量
		String str1="China";
		
		//2.根据字符串副本创建
		String str2 = new String("China");
		
		//3.根据字符数组创建字符串
		char []arr= {'d','a','d','f','g'};
		String str3 = new String(arr);
		
		//4.根据字符数组部分字符串创建字符串
		String str4 = new String(arr,1,3);
		
		System.out.println(str3+"    "+str4);
		
		//5.根据字节数组创建字符串
		byte[] bt = new byte[] {97,98,99};
		String str5 = new String(bt);
		System.out.println(str5);
		
		String str6 = "中国你好!!";
		byte[] bt02 = str6.getBytes();
		//6.根据byte数组以及指定的编码创建字符串
		String str7 = new String(bt02,"UTF-8");
		System.out.println(str7);
	}

}

12个String常用方法
split
public String[] split(String regex)
将此字符串拆分为给定的regular expression的匹配。

trim
public String trim()
返回一个字符串,其值为此字符串,并删除任何前导和尾随空格

length
public int length()
返回此字符序列的长度

charAt
public char charAt(int index)
返回char指定索引处的值

indexOf
public int indexOf(int ch)
返回指定字符第一次出现的字符串内的索引

substring
public String substring(int beginIndex,int endIndex)
返回一个字符串,该字符串是此字符串的子字符串

startsWith
public boolean startsWith(String prefix)
测试此字符串是否以指定的前缀开头。

endsWith
public boolean endsWith(String suffix)
测试此字符串是否以指定的后缀结尾。

compareTo
public int compareTo(String anotherString)
按字典顺序比较两个字符串。

getBytes
public byte[] getBytes()
使用平台的默认字符集将此String编码为字节序列,将结果存储到新的字节数组中。

equals
public boolean equals(Object anObject)
将此字符串与指定对象进行比较。

replace
public String replace(char oldChar,char newChar)
返回从替换所有出现的导致一个字符串oldChar在此字符串newChar

concat
public String concat(String str)
将指定的字符串连接到该字符串的末尾。

发布了66 篇原创文章 · 获赞 45 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/ACofKing/article/details/90108499