Reputation: 58
String add_filter = address.split("\\,", 2)[0];
This removes the text after the first comma. I need to remove the text after the second comma without using the loop.
Upvotes: 2
Views: 2968
Reputation: 119
try following code :
//Finding the Nth occurrence of a substring in a String
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
then you can remove string after this index position the same as following code :
String newStr = address.substring(0,ordinalIndexOf(address,",",2)- 1)
Upvotes: 1
Reputation: 93726
address.split("\\,")[2];
That splits the string around commas. THe 0th index is before the first comma, the 1st is after the 1st comma, the 2nd is after the 2nd comma, etc. Note that this code assumes there's at least 2 commas. If there aren't, you need to save the array returned by split() and check the length to make sure its 3 or higher. Otherwise there was no second comma.
Upvotes: 5
Reputation: 2558
Try below code
String s = "Hello,world,good bye";
s = s.replaceFirst(",(.*?),.*", " $1");
System.out.println(s);
Upvotes: 0