[英]remove the last part of a string in java
String Y="part1 part2 part3",X="part1";
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = useSplitToRemoveLastPart(Y);
if(Y.equals("")) {
break;
}
}
// useSplitToRemoveLastPart()的實現
private static String useSplitToRemoveLastPart(String y) {
//What goes here .. It should chop the last part of the string..
return null;
}
誰能幫忙......
如果您希望刪除part3並提供所有單詞由空格分隔
String str ="part1 part2 part3";
String result = str.substring(0,str.lastIndexOf(" "));
如果你真的想使用split:
private static String useSplitToRemoveLastPart(String str) {
String[] arr = str.split(" ");
String result = "";
if (arr.length > 0) {
result = str.substring(0, str.lastIndexOf(" " + arr[arr.length-1]));
}
return result;
}
public String removeLastSubstring(String target, String toRemove){
int idx = target.lastIndexOf(toRemove);
target = target.substring(0, idx) + target.substring(idx + toRemove.length());
return target;
}
您只需要將目標和要刪除的LAST子字符串傳遞給它,例如:
String s = "123 #abc# 456";
s = removeLastSubstring(s, "#abc#");
您的整個代碼可以優化為:
boolean foundmatch = y.startsWith(x);
y = foundmatch? x : "";
如果你想使用split進行 ,那么你可以這樣做:
String s[] = Y.split(" ");
String n = "";
for (int i = 0; i < s.length - 1; i++)
n+= s[i];
return n;
順便說一句,如果您需要構建的方法稱為useSplitToRemoveLastPart(String t)
,那么我建議您使用split來刪除最后一部分 。
看看這里 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.