Answers for "java replace substring between two strings"

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

java find substring between two strings

StringUtils.substringBetween(str, "<%=", "%>");
Posted by: Guest on September-18-2020

Code answers related to "java replace substring between two strings"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language