java中的string方法有哪些
1. Introduction在Java編程中,經(jīng)常會(huì)涉及到對(duì)字符串進(jìn)行各種操作。String類是Java中用于表示字符串的類,它提供了一系列的方法用于字符串的創(chuàng)建、修改、拼接、查找等操作。本文將詳細(xì)
1. Introduction
在Java編程中,經(jīng)常會(huì)涉及到對(duì)字符串進(jìn)行各種操作。String類是Java中用于表示字符串的類,它提供了一系列的方法用于字符串的創(chuàng)建、修改、拼接、查找等操作。本文將詳細(xì)介紹String類常用的幾個(gè)方法及其用法。
2. 創(chuàng)建字符串
String類提供了多種創(chuàng)建字符串的方法,包括直接賦值、構(gòu)造方法和靜態(tài)方法。下面是一些常用的創(chuàng)建字符串的方法示例:
- 直接賦值:
String str1 "Hello World";
- 使用構(gòu)造方法:
String str2 new String("Hello World");
- 使用靜態(tài)方法:
String str3 (123);
3. 字符串長度
獲取字符串的長度可以使用length()方法,示例如下:
String str "Hello World";
int length str.length(); // 返回11
4. 字符串比較
String類提供了多種比較字符串的方法,包括equals()、equalsIgnoreCase()、compareTo()等。示例如下:
String str1 "Hello";
String str2 "World";
boolean isEqual str1.equals(str2); // 返回false
int compareResult (str2); // 返回負(fù)數(shù)
5. 字符串查找
String類提供了多種查找子串相關(guān)的方法,包括indexOf()、lastIndexOf()、contains()等。示例如下:
String str "Hello World";
int index ("World"); // 返回6
boolean isContains ("ello"); // 返回true
6. 字符串替換
String類提供了replace()方法用于替換字符串中的指定部分。示例如下:
String str "Hello World";
String newStr ("World", "Baidu"); // 返回"Hello Baidu"
7. 字符串拼接
String類提供了多種拼接字符串的方法,包括concat()、 運(yùn)算符和StringBuilder/StringBuffer類。示例如下:
- 使用concat()方法:
String str1 "Hello";
String str2 "World";
String concatStr (str2); // 返回"HelloWorld"
- 使用 運(yùn)算符:
String str3 "Hello";
String str4 "World";
String plusStr str3 str4; // 返回"HelloWorld"
- 使用StringBuilder類:
StringBuilder sb new StringBuilder();
("Hello");
("World");
String sbStr (); // 返回"HelloWorld"
8. 字符串切割
String類提供了split()方法,用于將字符串按照指定的分隔符切割為字符串?dāng)?shù)組。示例如下:
String str "Hello,World";
String[] splitArray str.split(","); // 返回["Hello", "World"]
9. 字符串轉(zhuǎn)換
String類提供了多種轉(zhuǎn)換為其他類型的方法,包括toCharArray()、toLowerCase()、toUpperCase()等。示例如下:
String str "Hello World";
char[] charArray (); // 返回['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
String lowerCase (); // 返回"hello world"
String upperCase (); // 返回"HELLO WORLD"
10. 字符串格式化
String類提供了format()方法,用于按照指定的格式將參數(shù)轉(zhuǎn)換為字符串。示例如下:
String formatStr ("Hello, %s", "World"); // 返回"Hello, World"
11. 字符串截取
String類提供了substring()方法,用于截取指定索引范圍內(nèi)的子串。示例如下:
String str "Hello World";
String subStr (6); // 返回"World"
12. 總結(jié)
本文介紹了Java中String類的常用方法及其使用示例,包括字符串的創(chuàng)建、長度獲取、比較、查找、替換、拼接、切割、轉(zhuǎn)換、格式化和截取。掌握這些方法能夠高效地操作字符串,提高編程效率。希望讀者通過本文的學(xué)習(xí)能夠更好地應(yīng)用String類進(jìn)行字符串處理。