Shrestha Bibash
Shrestha Bibash

Reputation: 58

Remove string after second occurrence of comma in java

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

Answers (3)

Amin Rahkan
Amin Rahkan

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

Gabe Sechan
Gabe Sechan

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

Munir
Munir

Reputation: 2558

Try below code

String s = "Hello,world,good bye";
s = s.replaceFirst(",(.*?),.*", " $1");
System.out.println(s);

Upvotes: 0

Related Questions