'Split with specials character and print string value [closed]
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;
}
}
}
As i need below O/P
List item
String val1=Start//complete//First//com//upload the dummy123//First//download
String val2=First
Output=First//com//upload the dummy123//First//downloadList item
String val1=Start//complete//First//com//upload the dummy123//First//download
String val2=complete
Output=complete//First//com//upload the dummy123//First//downloadList item
String val1=Start//complete//First//com//upload the dummy123//First//download
String val2=com
Output=com//upload the dummy123//First//download
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Darkman |
