Java字符串有三種類型的替換方法
取代替換所有取代第一。在這些幫助下,您可以替換字符串中的字符。讓我們詳細研究一下:
1.Java字符串替換( )方法
描述:
此Java方法返回一個新字符串,該字符串是由用新字符替換每次出現的字符而產生的。
語法:
public Str replace(char oldC, char newC)
參數:
oldCh old character.(老掉牙的老字號)
newCh new character.(新的新角色)
返回值
此函數通過用newch替換oldCh來返回字符串。
例1
public class Guru99Ex1 {public static void main(String args[]) { String S1 = new String("the quick fox jumped"); System.out.println("Original String is ': " + S1); System.out.println("String after replacing 'fox' with 'dog': " + S1.replace("fox", "dog")); System.out.println("String after replacing all 't' with 'a': " + S1.replace('t', 'a')); }}
產出:
Original String is(原來的繩子是):the quick fox jumped (快跳的狐狸)
將'fox' with 'dog'(「狐狸」改為「狗」)後的字符串:the quick dog jumped(那隻敏捷的狗跳了起來)。
用「a」代替「t」之後的字符串:ahe quick fox jumped(一隻敏捷的狐狸跳了起來)
2.Java String Replaceall( )
描述
java String replaceAll()方法返回一個字符串,替換匹配正則表達式和替換字符串的所有字符序列。
籤署:
public Str replaceAll(String regex, String replacement)
參數:
regx: regular expression(正則表達式)
replacement: replacement sequence of characters(替換:替換字符序列)
例2
public class Guru99Ex2 {public static void main(String args[]) { String str = "Guru99 is a site providing free tutorials"; //remove white spaces String str2 = str.replaceAll("\s", ""); System.out.println(str2); }}
3.Java-String replaceFirst()方法
描述
該方法替換與該正則表達式匹配的給定字符串的第一個子字符串。
句法
public Str replaceFirst(String rgex, String replacement)
參數
rgex-給定字符串需要匹配的正則表達式。
替換替換正則表達式的字符串。
返回值
此方法將結果字符串作為輸出返回。
例3:
public class Guru99Ex2 {public static void main(String args[]) { String str = "This website providing free tutorials"; //Only Replace first 's' with '9' String str1 = str.replaceFirst("s", "9"); System.out.println(str1); }}
想了解更多的JAVA知識,記得關注小編哦!