字串廣泛地應用在Java程式設計中,在Java中字串屬於對象,Java 提供了String類別來建立和操作字串,本篇文章將詳細為大家介紹String類別的內容。
建立字串
建立字串最簡單的方式如下:
String greeting = "php中文網";
在程式碼中遇到字串常數時,這裡的值是"php中文網"",編譯器會使用該值建立一個String 物件。
#和其它物件一樣,可以使用關鍵字和建構方法來建立String 物件。
String 類別有11 種建構方法,這些方法提供不同的參數來初始化字串,例如提供一個字元陣列參數:
StringDemo.java 檔案程式碼:
public class StringDemo{ public static void main(String args[]){ char[] helloArray = { 'p', 'h', 'p'}; String helloString = new String(helloArray); System.out.println( helloString ); } }
以上實例編譯運行結果如下:
php
注意:String 類別是不可改變的,所以你一旦創建了String 對象,那它的值就無法改變了(詳看筆記部分解析)。
如果需要對字串做很多修改,那麼應該選擇使用StringBuffer & StringBuilder 類別。
字串長度
用於取得有關物件的資訊的方法稱為存取器方法。
String 類別的一個存取器方法是length() 方法,它會傳回字串物件包含的字元數。
下面的程式碼執行後,len變數等於14:
StringDemo.java 檔案程式碼:
public class StringDemo { public static void main(String args[]) { String site = "www.php.cn"; int len = site.length(); System.out.println( "php中文网网址长度 : " + len ); } }
以上實例編譯執行結果如下:
php中文网网址 : 14
連線字串
#String 類別提供了連接兩個字串的方法:
string1.concat(string2);
傳回string2 連接string1 的新字串。也可以對字串常數使用concat () 方法,如:
"我的名字是 ".concat("php");
更常用的是使用' '操作符來連接字串,如:
"Hello," + " php" + "!"
結果如下:
"Hello, runoob!"
下面是一個例子:
StringDemo.java 檔案程式碼:
public class StringDemo { public static void main(String args[]) { String string1 = "php中文网网址:"; System.out.println("1、" + string1 + "www.php.cn"); } }
以上實例編譯執行結果如下:
1、php中文网网址:www.php.cn
建立格式化字串
我們知道輸出格式化數字可以使用printf() 和format() 方法。
String 類別使用靜態方法format() 傳回String 物件而不是PrintStream 物件。
String 類別的靜態方法format() 能用來建立可重複使用的格式化字串,而不僅僅是用於一次列印輸出。
如下:
System.out.printf("浮点型变量的值为 " + "%f, 整型变量的值为 " + " %d, 字符串变量的值为 " + "is %s", floatVar, intVar, stringVar);
你也可以這樣寫
String fs; fs = String.format("浮点型变量的值为 " + "%f, 整型变量的值为 " + " %d, 字符串变量的值为 " + " %s", floatVar, intVar, stringVar)
String 方法
#下面是String 類別支援的方法,更多詳細,參考Java String API 文件:
SN(序號) | 方法描述 |
---|---|
1 | char charAt(int index) 傳回指定索引處的 char 值。 |
2 | int compareTo(Object o) 把這個字串和另一個物件比較。 |
3 | int compareTo(String anotherString) 按字典順序比較兩個字串。 |
4 | int compareToIgnoreCase(String str) 按字典順序比較兩個字串,不考慮大小寫。 |
5 | String concat(String str) 將指定字串連接到此字串的結尾。 |
6 | boolean contentEquals(StringBuffer sb) 當且僅當字串與指定的StringBuffer有相同順序的字元時候會傳回真。 |
7 | static String copyValueOf(char[] data) 傳回指定數組中表示該字元序列的 String。 |
8 | static String copyValueOf(char[] data, int offset, int count) 傳回指定數組中表示該字元序列的 String。 |
9 | boolean endsWith(String suffix) 測試此字串是否以指定的後綴結束。 |
10 | boolean equals(Object anObject) 將此字串與指定的物件進行比較。 |
11 | boolean equalsIgnoreCase(String anotherString) 將此 String 與另一個 String 比較,不考慮大小寫。 |
12 | byte[] getBytes() 使用平台的預設字元集將此 String 編碼為 byte 序列,並將結果儲存到一個新的 byte 陣列中。 |
13 | byte[] getBytes(String charsetName) 使用指定的字元集將此 String 編碼為 byte 序列,並將結果儲存到新的 byte 陣列中。 |
14 | void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 將字元從此字串複製到目標字元陣列。 |
15 | int hashCode() 傳回此字串的哈希碼。 |
16 | int indexOf(int ch) 傳回指定字元在此字串中第一次出現處的索引。 |
17 | int indexOf(int ch, int fromIndex) 傳回在此字串中第一次出現指定字元處的索引,從指定的索引開始搜尋。 |
18 | int indexOf(String str) 傳回指定子字串在此字串中第一次出現處的索引。 |
19 | int indexOf(String str, int fromIndex) 傳回指定子字串在此字串中第一次出現處的索引,從指定的索引開始。 |
20 | String intern() 傳回字串物件的規範化表示形式。 |
21 | int lastIndexOf(int ch) 傳回指定字元在此字串中最後一次出現處的索引。 |
22 | int lastIndexOf(int ch, int fromIndex) 傳回指定字元在此字串中最後一次出現處的索引,從指定的索引處開始進行反向搜尋。 |
23 | int lastIndexOf(String str) 傳回指定子字串在此字串中最右邊出現處的索引。 |
24 | int lastIndexOf(String str, int fromIndex) 傳回指定子字串在此字串中最後一次出現處的索引,從指定的索引開始反向搜尋。 |
25 | int length() 傳回此字串的長度。 |
26 | boolean matches(String regex) 告知此字串是否符合給定的正規表示式。 |
27 | boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 測試兩個字串區域是否相等。 |
28 | boolean regionMatches(int toffset, String other, int ooffset, int len) 測試兩個字串區域是否相等。 |
29 | String replace(char oldChar, char newChar) 傳回一個新的字串,它是透過用 newChar 替換此字串中出現的所有 oldChar 得到的。 |
30 | String replaceAll(String regex, String replacement) 使用給定的 replacement 替換此字串所有符合給定的正規表示式的子字串。 |
31 | String replaceFirst(String regex, String replacement) 使用給定的 replacement 來取代此字串符合給定的正規表示式的第一個子字串。 |
32 | String[] split(String regex) 根據給定正則表達式的匹配拆分此字串。 |
33 | String[] split(String regex, int limit) 根據符合給定的正規表示式來拆分此字串。 |
34 | boolean startsWith(String prefix) 測試此字串是否以指定的前綴開始。 |
35 | boolean startsWith(String prefix, int toffset) 測試此字串從指定索引開始的子字串是否以指定前綴開始。 |
36 | CharSequence subSequence(int beginIndex, int endIndex) 傳回一個新的字元序列,它是此序列的一個子序列。 |
37 | String substring(int beginIndex) 傳回一個新的字串,它是此字串的一個子字串。 |
38 | String substring(int beginIndex, int endIndex) 傳回一個新字串,它是此字串的一個子字串。 |
39 | char[] toCharArray() 將此字串轉換為一個新的字元陣列。 |
40 | String toLowerCase() 使用預設語言環境的規則將此 String 中的所有字元轉換為小寫。 |
41 | String toLowerCase(Locale locale) 使用給定 Locale 的規則將此 String 中的所有字元轉換為小寫。 |
42 | String toString() 傳回此物件本身(它已經是一個字串!)。 |
43 | String toUpperCase() 使用預設語言環境的規則將此 String 中的所有字元轉換為大寫。 |
44 | String toUpperCase(Locale locale) 使用給定 Locale 的規則將此 String 中的所有字元轉換為大寫。 |
45 | String trim() 傳回字串的副本,忽略前導空白和尾部空白。 |
46 | static String valueOf(primitive data type x) 傳回給定data type類型x參數的字串表示形式。 |
相關推薦:
詳細分析Java中String、StringBuffer、StringBuilder類別的效能
java 中Math 與String format 類別實例詳解
#以上是Java中String類別的詳細解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java實現“一次編寫,到處運行”通過編譯成字節碼並在Java虛擬機(JVM)上運行。 1)編寫Java代碼並編譯成字節碼。 2)字節碼在任何安裝了JVM的平台上運行。 3)使用Java原生接口(JNI)處理平台特定功能。儘管存在挑戰,如JVM一致性和平台特定庫的使用,但WORA大大提高了開發效率和部署靈活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。