Split string by char in java

2020-03-10 05:27发布

问题:

I'm getting a string from the web looking like this:

Latest Episode@04x22^Killing Your Number^May/15/2009

Then I need to store 04x22, Killing Your Number and May/15/2009 in diffent variables, but it won't work.

String[] all = inputLine.split("@");
String[] need = all[1].split("^");
show.setNextNr(need[0]);
show.setNextTitle(need[1]);
show.setNextDate(need[2]);

Now it only stores NextNr, with the whole string

04x22^Killing Your Number^May/15/2009

What is wrong?

回答1:

String.split(String regex)

The argument is a regualr expression, and ^ has a special meaning there; "anchor to beginning"

You need to do:

String[] need = all[1].split("\\^");

By escaping the ^ you're saying "I mean the character '^' "



回答2:

If you have a separator but you don't know if it contains special characters you can use the following approach

String[] parts = Pattern.compile(separator, Pattern.LITERAL).split(text);


回答3:

Using guava, you can do it elegantly AND fast:

private static final Splitter RECORD_SPLITTER = Splitter.on(CharMatcher.anyOf("@^")).trimResults().omitEmptyStrings();

...

Iterator<String> splitLine = Iterables.skip(RECORD_SPLITTER.split(inputLine), 1).iterator();

show.setNextNr(splitLine.next());
show.setNextTitle(splitLine.next());
show.setNextDate(splitLine.next());


回答4:

public static String[] split(String string, char separator) {
    int count = 1;
    for (int index = 0; index < string.length(); index++)
        if (string.charAt(index) == separator)
            count++;
    String parts[] = new String[count];
    int partIndex = 0;
    int startIndex = 0;
    for (int index = 0; index < string.length(); index++)
        if (string.charAt(index) == separator) {
            parts[partIndex++] = string.substring(startIndex, index);
            startIndex = index + 1;
        }
    parts[partIndex++] = string.substring(startIndex);
    return parts;
}


回答5:

String input = "Latest Episode@04x22^Killing Your Number^May/15/2009";

//split will work for both @ and ^
String splitArr[] = input.split("[@\\^]");

/*The output will be,
 [Latest Episode, 04x22, Killing Your Number, May/15/2009]
*/
System.out.println(Arrays.asList(splitArr));