標籤:uil ack tchar tin stl com junit pre his
package day01;import org.junit.Test;public class TestString {/** * 測試常量池 * * */@Testpublic void testConstantPool(){String str1 = "Hello";//String str2 = "Hello";//兩個對象使用==進行比較,傳回值為true 說明兩個對象引用 指向的記憶體地區相同System.out.println(str1 == str2);String str3 = new String("Hello");//說明兩個對象引用 指向的記憶體地區 不 相同,使用new建立的字串 不會緩衝在String//常量池System.out.println(str1 == str3);}/* * 擷取String 對象的長度 */@Testpublic void testLength(){String str1 = "Hello";System.out.println(str1.length());//在記憶體中採用Unicode編碼 每個位元組2個字元//任何一個字元都算一個長度String str2 = "你好,String";System.out.println(str2.length());}/* * 字串截取 */@Testpublic void testSubstring(){String str = "http://www.oracle.com";String substr = str.substring(11, 17);System.out.println(substr);}/* * 去掉空格Trim * */@Testpublic void testTrim(){String userName = " good man";System.out.println(userName.length());userName = userName.trim();System.out.println(userName.length());System.out.println(userName);}/* * 遍曆字串中的字元序列 */@Testpublic void testCharAt(){String name = "xuejingbo";for (int i=0;i<name.length();i++){char c = name.charAt(i);System.out.print(c+ " ");}}//endWith 以特定字元結束 startsWidth 以**開始//toLowerCase//toUpperCase//將其他類型的轉為字串//String 類的valueOf 重載的方法,可以將double類型,int類型,Boolean及char//類型轉變為String類變數@Testpublic void testValueOf(){double pi = 3.1415926;int value = 123;boolean flag = true;char[] charArr = {‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘};String str = String.valueOf(pi);System.out.println(str);str = String.valueOf(value);System.out.println(str);}/* * 測試StringBuilder append */@Testpublic void testAppend(){StringBuilder sb = new StringBuilder("programing language:");sb.append("java").append("cpp").append("php").append("c#");System.out.println(sb.toString());}/* * 測試StringBuilder insert */@Testpublic void testInsert(){StringBuilder sn = new StringBuilder("thisisatest");sn.insert(5, "html");System.out.println(sn);}}
Java 中的字串 操作