String 類常用方法

2021-07-05 09:37:50 字數 2316 閱讀 6749

/*

* 字串:就是由多個字元組成的一串陣列

* 一旦被複製,就不能被改變

* */

public class stringdemo ;

string s2 = new string(bys);

system.out.println("s2:" + s2);

system.out.println("s2.length():" + s2.length()); // 5

system.out.println("----");

// public string (byte bytes,int index,int length);

string s3 = new string(bys, 0, 3);

system.out.println("s3:" + s3);

system.out.println("s3.length():" + s3.length()); // 3

system.out.println("----");

// public string(char value)

char chs = ;

string s4 = new string(chs);

system.out.println("s4:" + s4);

system.out.println("s4.length():" + s4.length()); // 8

system.out.println("----");

// public string(char value,int index,int count);

string s5 = new string(chs, 2, 6);

system.out.println("s5:" + s5);

system.out.println("s5.length():" + s5.length()); // 6

system.out.println("---");

/**

*/string ss1 = "hello";

string ss2 = "beautiful";

ss1 += "world";

ss2 += ss1;

system.out.println("ss1:" + ss1);

system.out.println("ss2:" + ss2);

/*

*  */

string ss3 = new string("hello");

string ss4 = "hello";

system.out.println(ss3 == ss4); //false

system.out.println(ss3.equals(ss4)); //true

system.out.println("----");

/* * 字串變數想家:先開空間,再拼接;

* 字串常量想家,先加,再在常量池找,有就返回,否則建立;

*/string sss1 = "hello";

string sss2 = "world";

string sss3 = "helloworld";

system.out.println(sss3 == sss1+sss2);  //false

system.out.println(sss3.equals(sss1+sss2));  //true

system.out.println(sss3 == "hello"+"world");  //true

system.out.println(sss3.equals("hello"+"world"));  //true

}}

結果:
s1:

s1.length():0

----

s2:abcde

s2.length():5

----

s3:abc

s3.length():3

----

s4:abcde我愛你

s4.length():8

----

s5:cde我愛你

s5.length():6

---ss1:helloworld

ss2:beautifulhelloworld

---false

true

---false

true

true

true

String類常用方法

方法名稱 型別 方法描述 public string char value 構造 將字元陣列變為string類物件 public string char value,int offset int count 構造 將部分字元陣列變為string類物件 public char charat int i...

String類常用方法

返回字串長度 public int length 返回字串中指定位置的字元 public char charat int index 提取字串 方法說明 public string substring int beginindex 從beginindex位置起,從當前字串中取出剩餘的字元作為乙個新的...

String類常用方法

string 不可變長的字串行 在做字串拼接的時候會直接在堆中建立乙個新的字串物件,並使用這個字串物件儲存新的值,指標直接指向新的字串物件的位址。stringbuilder 可變長的字串行,執行緒不安全,效率較高 stringbuffer 可變長的字串行,執行緒安全,效率較低 string byte...