开发者

How to split a string using a char array separator in java?

like c#:

string[] Split(char[] separator, StringSplitOptions开发者_Go百科 options)

is there an equivalent method in java?


This does what you want:

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));
}

Output (including the final regex for information/interest only):

(\,|\^|\*|\/|\+|\-|\&|\=|\<|\>|\=|\%|\(|\)|\{|\}|\;)
[foo, bar, hello, world]


Take a look at public String[] split(String regex) and java.util.regex.


String[] split(String)

You can turn a char[] into a String with String(char[]).


Possibly you want this. I'm not sure:

    String text = "abcdefg";
    System.out.println(Arrays.toString(text.split("d|f|b")));

Results in:

   [a, c, e, g]


Another level up in functionality is Guava's Splitter:

Splitter splitOnStuff = Splitter.on(CharMatcher.anyOf("|,&"))
                                .omitEmptyStrings();

Iterable<String> values = splitOnStuff.split("value1&value2|value3,value4");


You have to use Regex, to achieve this. It will tell this on which basis you have to separate. Like there is OR "|" operator. If you use

String regex = "a|b|c";
String[] tokens = str.split(regex)

It will split on a,b & c basis.


Goold ol' StringTokenizer will do it too:

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());
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜