How to replace first occurrence of string in Java

后端 未结 6 1046
悲&欢浪女
悲&欢浪女 2020-11-29 07:20

I want to replace first occurrence of String in the following.

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

**If test c

6条回答
  •  余生分开走
    2020-11-29 07:45

    You can use following method.

    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;
    
    }
    

    Following link provide examples for replacing first occurrence of string using with and without regular expressions.

提交回复
热议问题