Java 中的字串 操作

來源:互聯網
上載者:User

標籤: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 中的字串 操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.