I have words like:
Sams – like costco
Jecy penny ? like sears
In Java I want to take this string and get the out put as:
Sams
Jecy penny
Is there any way I can remove all characters after -
and ?
?
I have words like:
Sams – like costco
Jecy penny ? like sears
In Java I want to take this string and get the out put as:
Sams
Jecy penny
Is there any way I can remove all characters after -
and ?
?
Three options:
indexOf
and then substring
split
and then take the first return valueHere's the split option - bear in mind that split
takes a regular expression:
public class Test {
public static void main(String[] args) {
showFirstPart("Sams - like costco");
showFirstPart("Jecy penny ? like sears");
}
private static void showFirstPart(String text) {
String[] parts = text.split("[-?]", 2);
System.out.println("First part of " + text
+ ": " + parts[0]);
}
}
1. Sams - like costco
Answer:
String s = "Sams - like costco";
String[] arr = s.split("-");
String res = arr[0];
2. Jecy penny ? like sears
Answer:
String s = "Jecy penny ? like sears";
String[] arr = s.split("\\?");
Added \\ before ?, as ? has a special meaning
String res = arr[0];
Though the above 2 examples are for those with only one "-" and "?", you can do this for multiple "-" and "?" too
Use String.split()
method
String str = "Sams – like costco";
String str1 = "Jecy penny ? like sears";
String[] arr = str.split("–");
String arr1[] = str1.split("\\?");
System.out.println(arr[0]);
System.out.println(arr1[0]);
I've assumed that you want to remove the word "like"
and the following word after either "-"
or "?"
...
Here's how you do it in one line:
String output = input.replaceAll( "(?i)[-?]\\s*like\\s+\\b.+?\\b", "" );
Here's some test code:
public static void main( String[] args ) {
String input = "Sams - like costco Jecy penny ? like sears";
String output = input.replaceAll( "(?i)[-?]\\s*like\\s+\\b.+?\\b", "" );
System.out.println( output );
}
Output:
Sams Jecy penny