Here is my attempt.
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();
}
Using the above method for:
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);
it gives output:
First//com//upload//First//download
EDIT:
I just realised from the comment that it could be done easier with the following:
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);
EDIT 2:
And here’s another one-liner way.
val1.replaceFirst(".*?" + val2, val2)
1
solved Split with specials character and print string value [closed]