1. 程式人生 > 其它 >String類 字串的生成和關於字串的常用方法總結

String類 字串的生成和關於字串的常用方法總結

技術標籤:字串java資料結構

String類 字串的生成和關於字串的常用方法總結

一、字串的特點:

  1. 字串的內容永不可變
  2. 正因為字串不可改變,所以字串師可以共享使用的。
  3. 字串效果上相當於char[ ] 字元陣列,但是底層原理師byte[ ]位元組陣列。
  4. 對於字串是引用型別,使用 == 是進行地址值的比較,內容比較應該使用equals()

二、字串的生成方法
三種構造方法和一種直接建立

  1. pubic String(),建立一個空白字串
  2. public String(char [ ] arr),根據字元陣列的內容來建立對應的字串
  3. public String(byte[ ] arr ),根據位元組陣列的內容,來建立對應的字串
  4. String str = “ ”;直接建立;
public static void main(String[] args) {
		// pubic String(),建立一個空白字串
		String str1 = new String();
		
//		public String(char [ ] arr),根據字元陣列的內容來建立對應的字串
		char[] c = {'c','b','a'};
		String str2 = new String(c);
		
//		public  String(byte[ ] arr ),根據位元組陣列的內容,來建立對應的字串
		
		byte[] b =
{97,98,99}; String str3 = new String(b); // String str4 = "bca"; 直接建立 String str4 = "bca"; System.out.println(str1); System.out.println(str2); System.out.println(str3); System.out.println(str4); }

三、常用的相關方法

返回型別方法
intlength()
Stringconcat(String str)
charcharAt(int index)
intindexof(String str)
  1. length() 獲取字串中含有字元個數,拿到字串的長度。
  2. concat(String str) 將兩個字串拼接成新的字串。
  3. chatAt(int index) 獲取指定索引位置的單個字元。
  4. indexOf(String str)
public static void main(String[] args) {
	
	//獲取字串的長度
	String str = "flakjflkaj";
	System.out.println("字串的長度:"+str.length());//10
	
	//拼接字串
	String str1 = "Hello";
	String str2 = "World";
	String str3 = str1.concat(str2);//HelloWorld
	System.out.println(str3);
	System.out.println("+++++++++");
	//獲取指定索引位置的單個字元
	char c = str1.charAt(1);
	System.out.println("在1號索引位置的字元是:"+c);//e
	System.out.println("==========");
	
	//查詢引數字串在本來字串當中出現的第一次索引位置
	//如果根本沒有,返回-1值
	int index = str3.indexOf("llo");
	System.out.println(index);//2
	
	
	}

在這裡插入圖片描述