此代码删除字符串参数中的第一个“ abc”,并返回结果字符串。
I'm just confused because I'm just returning an empty string because I wrote String
instead of void
. I would have used System.out.println();
along with break;
if I wrote void
but I just didn't because I used it in an exercise and it said bad code(even though the results are same). Would be glad if you have any opinions.
This is my code below;
public static String abc(String str) {
int i = 0;
while(i < str.length()-2) {
if (str.substring(i, i+3).equals("abc")) {
return str.substring(0, i) + str.substring(i+3);
} else {
if (i == str.length()-3) {
return str;
}
} i++;
} return "";
For information on manipulating strings see the Java String API:https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html
您可以用更少的代码来实现相同的目的: