日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1.10 字符串的替换(replace()、replaceFirst()和replaceAll())

發(fā)布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 1.10 字符串的替换(replace()、replaceFirst()和replaceAll()) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在 Java 中,String 類提供了 3 種字符串替換方法,分別是 replace()、replaceFirst() 和 replaceAll(),本文將詳細介紹它們的使用方法。

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

總結

以上是生活随笔為你收集整理的1.10 字符串的替换(replace()、replaceFirst()和replaceAll())的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。