public class SplitStringobj {
public static void main(String[] args) {
String val1= Start//complete//First//com//upload the dummy123//First//download;
String val2= First;
String[] splitObject = outObject.split("//");
for(String obj :splitObject) {
if(outObject.startsWith(obj.toString());
break;
}
}
}
因为我需要低于 O/P
列表项
String val1=Start//complete//First//com//上传dummy123//First//下载
String val2=First
output=First//com//上传dummy123//First//下载列表项
String val1=Start//complete//First//com//上传dummy123//First//下载
String val2=complete
output=complete//First//com//上传dummy123//First//下载列表项
String val1=Start//complete//First//com//上传dummy123//First//下载
String val2=com
output=com//上传dummy123//先//下载
回答1
这是我的尝试。
public static String first_match(String[] str, String toMatch) {
boolean match = false;
StringBuilder output = new StringBuilder();
for (int i=0; i<str.length; i++) {
if (str[i].equals(toMatch)) {
match = true;
}
if (match){
output.append(str[i]);
if (i != str.length-1) {
output.append("//");
}
}
}
return output.toString();
}
使用上述方法:
String val1 = "Start//complete//First//com//upload//First//download";
String val2 = "First";
String[] splitObject = val1.split("//");
String out = first_match(splitObject, val2);
System.out.println(out);
它给出输出:
First//com//upload//First//download
编辑:
我刚刚从评论中意识到,使用以下方法可以更轻松地完成:
public static String firstMatch(String str, String toMatch) {
int index = str.indexOf(toMatch);
if (index == -1) return "";
return str.substring(index);
}
String out1 = firstMatch(val1, val2);
编辑 2:
这是另一种单行方式。
val1.replaceFirst(".*?" + val2, val2)