Casper
Casper

Reputation: 373

Split string by char in java

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?

Upvotes: 14

Views: 65162

Answers (5)

Yogi
Yogi

Reputation: 1712

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

Upvotes: 1

Michael Manner
Michael Manner

Reputation: 532

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

Upvotes: 1

Agoston Horvath
Agoston Horvath

Reputation: 791

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

Upvotes: 7

Peter Lawrey
Peter Lawrey

Reputation: 533492

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

Upvotes: 23

Brian Roach
Brian Roach

Reputation: 76898

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 '^' "

Upvotes: 33

Related Questions