Answers for "substring and replace in java"

1

java replace substring between two strings

/**
     * 
     * @param firstString the string where you wan
     * @param lastString
     * @param occurence
     * @param replace the string between the firstString and lastString
     * @param stringBody this is the whole string 
     * @return 
     */
   public static String replaceStringBtwn(String stringBody, int occurence, String firstString, String lastString, String replace) {

        StringBuilder firstPart = new StringBuilder();
        StringBuilder lastPart = new StringBuilder();

        int partPortion = 1;

        int occurenceEncountered = 1;

        for (String elem : stringBody.split("\n")) {

            if (partPortion == 1 && !elem.contains(firstString)) {
                firstPart.append(elem + "\n");
                continue;
            }
            if (partPortion == 2) {
                lastPart.append(elem + "-\n");
                continue;
            }

            if (elem.contains(firstString)) {
                if (occurence == occurenceEncountered) {
                    firstPart.append(firstString);
                    firstPart.append(replace);
                    firstPart.append(lastString);
                    firstPart.append("\n");
                    partPortion = 2;
                    occurence = occurence + 1;
                }
                occurenceEncountered = occurenceEncountered + 1;
                continue;
            }
        }
        return firstPart.append(lastPart).toString();
    }
Posted by: Guest on September-23-2021
-1

string.replace in java

public static void main(String args[]){  
String s1="my name is khan my name is java";  
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"  
System.out.println(replaceString);  
}}
Posted by: Guest on June-21-2021

Code answers related to "substring and replace in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language