簡體   English   中英

如何替換Java中第一次出現的字符串

[英]How to replace first occurrence of string in Java

我想在下面替換第一次出現的字符串。

String test = "see Comments, this is for some test, help us"

**如果測試包含如下輸入,則不應替換

  1. 見評論,(末尾有空格)
  2. 看評論,
  3. 看評論**

我想得到如下輸出,

Output: this is for some test, help us

您應該使用已經過測試且文檔齊全的庫來編寫自己的代碼。

org.apache.commons.lang3.
  StringUtils.replaceOnce("coast-to-coast", "coast", "") = "-to-coast"

Javadoc

甚至還有一個不區分大小寫的版本(這很好)。

馬文

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.7</version>
</dependency>

學分

我的回答是對以下內容的擴充: https : //stackoverflow.com/a/10861856/714112

您可以使用以下語句將第一次出現的文字字符串替換為另一個文字字符串:

String result = input.replaceFirst(Pattern.quote(search), Matcher.quoteReplacement(replace));

但是,這在后台做了很多工作,而用專門的函數來替換文字字符串則不需要這些工作。

使用substring(int beginIndex)

String test = "see Comments, this is for some test, help us";
String newString = test.substring(test.indexOf(",") + 2);
System.out.println(newString);

輸出:

這是為了一些測試,幫助我們

您可以使用以下方法。

public static String replaceFirstOccurrenceOfString(String inputString, String stringToReplace,
        String stringToReplaceWith) {

    int length = stringToReplace.length();
    int inputLength = inputString.length();

    int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);

    String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
            + inputString.substring(startingIndexofTheStringToReplace + length, inputLength);

    return finalString;

}

以下鏈接提供了使用正則表達式和不使用正則表達式替換第一次出現的字符串的示例。

使用 String replaceFirst 將分隔符的第一個實例交換為唯一的:

String input = "this=that=theother"
String[] arr = input.replaceFirst("=", "==").split('==',-1);
String key = arr[0];
String value = arr[1];
System.out.println(key + " = " + value);

你也可以在node.js中使用這個方法;

public static String replaceFirstOccurance(String str, String chr, String replacement){
    String[] temp = str.split(chr, 2);
    return temp[0] + replacement + temp[1];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM