user1899174
user1899174

Reputation: 279

Remove characters before a comma in a string

I was wondering what would be the best way to go about removing characters before a comma in a string, as well as removing the comma itself, leaving just the characters after the comma in the string, if the string is represented as 'city,country'.

Thanks in advance

Upvotes: 13

Views: 39238

Answers (5)

Daniel Kaplan
Daniel Kaplan

Reputation: 67320

So you want

city,country

to become

country

An easy way to do this is this:

public static void main(String[] args) {
    System.out.println("city,country".replaceAll(".*,", ""));
}

This is "greedy" though, meaning it will change

city,state,country

into

country

In your case, you might want it to become

state,country

I couldn't tell from your question.

If you want "non-greedy" matching, use

System.out.println("city,state,country".replaceAll(".*?,", ""));

this will output

state, country

Upvotes: 35

Bassem Reda Zohdy
Bassem Reda Zohdy

Reputation: 12942

check this

String s="city,country";
System.out.println(s.substring(s.lastIndexOf(',')+1));

I found it faster than .replaceAll(".*,", "")

Upvotes: 4

tobias_k
tobias_k

Reputation: 82899

This can be done with a combination of substring and indexOf, using indexOf to determine the position of the (first) comma, and substring to extract a portion of the string relative to that position.

String s = "city,country";
String s2 = s.substring(s.indexOf(",") + 1);

Upvotes: 2

Orion
Orion

Reputation: 111

If what you are interested in is extracting data while leaving the original string intact you should use the split(String regex) function.

String foo = new String("city,country");
String[] data = foo.split(",");

The data array will now contain strings "city" and "country". More info is available here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29

Upvotes: 4

Tdorno
Tdorno

Reputation: 1571

You could implement a sort of substring that finds all the indexes of characters before your comma and then all you'd need to do is remove them.

Upvotes: 0

Related Questions