在Java中,String 類提供了 3 種字符串替換方法,分別是 replace()、replaceFirst() 和 replaceAll(),下面我們就來詳細看一下三種的用法!
????下面這套Java300集視頻專門為零基礎而制,適合準備入行Java開發(fā)的零基礎,視頻中穿插多個實戰(zhàn)項目。每一個知識點都講解的通俗易懂,由淺入深。不僅適用于零基礎的初學者,有經(jīng)驗的程序員也可做鞏固學習。
replace() 方法
????????replace() 方法用于將目標字符串中的指定字符(串)替換成新的字符(串),其語法格式如下:
字符串.replace(String oldChar, String newChar)
????????其中,oldChar 表示被替換的字符串;newChar 表示用于替換的字符串。replace() 方法會將字符串中所有 oldChar 替換成 newChar。
例 1:
????????創(chuàng)建一個字符串,對它使用 replace() 方法進行字符串替換并輸出結果。代碼如下:
public static void main(String[] args) {
? ? String words = "hello java,hello php";
? ? System.out.println("原始字符串是'"+words+"'");
? ? System.out.println("replace(\"l\",\"D\")結果:"+words.replace("l","D"));
? ? System.out.println("replace(\"hello\",\"你好\")結果:"+words.replace("hello","你好 "));
? ? words = "hr's dog";
? ? System.out.println("原始字符串是'"+words+"'");
? ? System.out.println("replace(\"r's\",\"is\")結果:"+words.replace("r's","is"));
}
????????輸出結果如下所示:
原始字符串是'hello java,hello php'
replace("l","D")結果:heDDo java,heDDo php
replace("hello","你好")結果:你好 java,你好 php
原始字符串是'hr's dog'
replace("r's","is")結果:his dog
replaceFirst() 方法
????????replaceFirst() 方法用于將目標字符串中匹配某正則表達式的第一個子字符串替換成新的字符串,其語法形式如下:
字符串.replaceFirst(String regex, String replacement)
????????其中,regex 表示正則表達式;replacement 表示用于替換的字符串。例如:
String words = "hello java,hello php";
String newStr = words.replaceFirst("hello","你好 ");
System.out.println(newStr);? ? // 輸出:你好 java,hello php
replaceAll() 方法
????????replaceAll() 方法用于將目標字符串中匹配某正則表達式的所有子字符串替換成新的字符串,其語法形式如下:
字符串.replaceAll(String regex, String replacement)
其中,regex 表示正則表達式,replacement 表示用于替換的字符串。例如:
String words = "hello java,hello php";
String newStr = words.replaceAll("hello","你好 ");
System.out.println(newStr);? ? // 輸出:你好 java,你好 php文章來源:http://www.zghlxwxcb.cn/news/detail-676765.html
????????Java字符串的替換主要就是這樣了,多多練習。文章來源地址http://www.zghlxwxcb.cn/news/detail-676765.html
到了這里,關于Java中的字符串替換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!