简体   繁体   中英

changing value of a variable inside catch block

Here's the code:

public static String removeDateFromString(String txt) {
    String dateRemovedString = new String();
    String[] str = txt.split("-");

    for(int i=0; i<str.length; i++) {

        SimpleDateFormat format = new SimpleDateFormat("dd MMM");
        try {
            format.parse(str[i]);
        } catch(ParseException e) {
            dateRemovedString.concat(str[i]);
        }
    }
    return dateRemovedString;
}

For,

input text: Cricket Match - 01 Jul

output text: "" (empty String)

But I want, output: Cricket Match

What should I do?

String is immutable :

Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation.

dateRemovedString = dateRemovedString.concat(str[i]);

StringBuilder is mutable. StringBuilder is used to build a String. Use StringBuilder instead in this case. Example usage:

StringBuilder dateRemovedString = new StringBuilder();
dateRemovedString.append(str[i]);
return dateRemovedString.toString();

If you are sure about the input text format, then don't bother to hit the exception.

Simply extract the part you are interested using split or RegExp and then process it

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