Java 删除字符串中逗号前的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16285485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove characters before a comma in a string
提问by user1899174
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
提前致谢
采纳答案by Daniel Kaplan
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
州,国家
回答by Tdorno
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.
您可以实现一种子字符串来查找逗号之前的所有字符索引,然后您需要做的就是删除它们。
回答by Orion
If what you are interested in is extracting data while leaving the original string intact you should use the split(String regex) function.
如果您感兴趣的是在保留原始字符串完整的同时提取数据,您应该使用 split(String regex) 函数。
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
数据数组现在将包含字符串“city”和“country”。此处提供更多信息:http: //docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29
回答by tobias_k
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.
这可以用的组合来完成substring
,并indexOf
使用indexOf
以确定(第一)逗号的位置,并且substring
提取相对于该位置的串的一部分。
String s = "city,country";
String s2 = s.substring(s.indexOf(",") + 1);
回答by Bassem Reda Zohdy
check this
检查这个
String s="city,country";
System.out.println(s.substring(s.lastIndexOf(',')+1));
I found it faster than .replaceAll(".*,", "")
我发现它比 .replaceAll(".*,", "")