gpt4 book ai didi

java - 更改 catch block 内变量的值

转载 作者:搜寻专家 更新时间:2023-11-01 04:06:11 25 4
gpt4 key购买 nike

代码如下:

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

对于,

输入文本:板球比赛 - 7 月 1 日

输出文本:""(空字符串)

但我想要,输出:Cricket Match

我该怎么办?

最佳答案

字符串是 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 是可变的。 StringBuilder 用于构建 字符串。在这种情况下,请改用 StringBuilder。用法示例:

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

关于java - 更改 catch block 内变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16786154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com