如C#:如何在java中使用char数组分隔符来分割字符串?
string[] Split(char[] separator, StringSplitOptions options)
有在Java等效的方法?
如C#:如何在java中使用char数组分隔符来分割字符串?
string[] Split(char[] separator, StringSplitOptions options)
有在Java等效的方法?
这你想要做什么:
public static void main(String[] args) throws Exception
{
char[] arrOperators = { ',', '^', '*', '/', '+', '-', '&', '=', '<', '>', '=', '%', '(', ')', '{', '}', ';' };
String input = "foo^bar{hello}world"; // Expecting this to be split on the "special" chars
String regex = "(" + new String(arrOperators).replaceAll("(.)", "\\\\$1|").replaceAll("\\|$", ")"); // escape every char with \ and turn into "OR"
System.out.println(regex); // For interest only
String[] parts = input.split(regex);
System.out.println(Arrays.toString(parts));
}
输出(包括仅用于信息/感兴趣的最终正则表达式):
(\,|\^|\*|\/|\+|\-|\&|\=|\<|\>|\=|\%|\(|\)|\{|\}|\;)
[foo, bar, hello, world]
String[] split(String)
你可以把一个char[]
成字符串String(char[]).
看看public String[] split(String regex)
和java.util.regex
。
可能你想要这个。我不知道:
String text = "abcdefg";
System.out.println(Arrays.toString(text.split("d|f|b")));
结果:
[a, c, e, g]
在功能上另一个层次了是番石榴的Splitter:
Splitter splitOnStuff = Splitter.on(CharMatcher.anyOf("|,&"))
.omitEmptyStrings();
Iterable<String> values = splitOnStuff.split("value1&value2|value3,value4");
Goold ol'StringTokenizer也会这样做:
public static void main(String[] args) {
String delim = ",^*/+-&=<>=%(){};";
String str = "foo^bar{hello}world";
StringTokenizer tok = new StringTokenizer(str, delim);
while (tok.hasMoreTokens()) {
System.out.println(tok.nextToken());
}
}
太好了。有用。谢谢。这可以被接受为标准答案。 – guhai