简体   繁体   中英

Extracting variable outside of a loop in a method

This is a method to basically get rid of html tags in some text. the method remove is given by the following and I tested it and it works.

    public static String remove(String text, String str) {

    int firstIndex = text.indexOf(str);
    int beginofNewIndex = (firstIndex + 1) + str.length();

    if (firstIndex > 0) {
        return text.substring(0, firstIndex) + text.substring(beginofNewIndex);
    } else {
        return text;
    }
} 

However, when I return "text" as given below, it gives me the same value as when I input it. So let's say the parameter for the method removeAllTags is String text. I input "< b> The boy walked < /b >" but it returns the same thing. Does anyone see anything wrong?

    public static String removeAllTags(String text) {

    int textLength = text.length();

    while (textLength > 2) {
        int firstIndex = text.indexOf("<");
        int secondIndex = text.indexOf(">");
        int thirdIndex = text.indexOf("</", secondIndex);
        int fourthIndex = text.indexOf(">", secondIndex);

        if (firstIndex >= 0 && secondIndex >= 0 && thirdIndex >= 0 && fourthIndex >= 0F) {


            remove(text, text.substring(firstIndex, (secondIndex + 1)));
            // remove(text, text.substring(thirdIndex, (fourthIndex + 1))); I will implement this into the code but I am testing with the first remove method first.



        }
        textLength = textLength - 1;
    }
    return text;

}

The key problem is this line:

remove(text, text.substring(firstIndex, (secondIndex + 1)));

This does nothing.

Java does not pass by reference like C, and Strings are immutable, so any changes made to strings passed in are not reflected outside the method.

Instead, you must assign the result back to the variable:

text = remove(text, text.substring(firstIndex, (secondIndex + 1)));

Whatever other problems there may be with your code, this one is the biggest.

The problem is your string and condition

"< b> The boy walked < /b >" 

this string of yours has space between < space /b>, this gives false result for

int thirdIndex = text.indexOf("</", secondIndex);

that's why it does not go into the loop and you need to assign text with the returned text

text = remove(text, text.substring(firstIndex, (secondIndex + 1)));

You can also use regular expression to remove all html tag

str.replaceAll("\\<.*?>","")
try this give your comment
change these lines
int beginofNewIndex = (firstIndex) + str.length();
this will point new char after >
and
if (firstIndex >= 0) 
this will accept when < is in first index like <br>hai.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM