0

I am given this 2 lines where the second line has a tab right after 'a',

    a b C d
    a[tab]b c d

The result I want is:

First Line: "a", " bcd"
Second Line: "a", "[tab]b c d"

I have to use only one split function and I had tried split("\\s+", 2), but it didn't work as expected.

mike
  • 9
  • 2
  • 1
    "it didn't work as expected" doesn't tell us what it *did* do... – Jon Skeet Mar 26 '14 at 15:36
  • split("\\s+", 2) gives me this result: First Line: "a", "bcd" Second Line: "a", "b c d" – mike Mar 26 '14 at 15:39
  • Mike, giving one example is not a sufficient definition of the problem. You have the explain how you want to split as well. As you can see from @BheshGurung there is easily more than one interpretation of this, which would yield different results for different examples, but the same result for this one. – Cruncher Mar 26 '14 at 15:42

3 Answers3

3

To keep the tab or space you need to use look-ahead, and split like this:

String[] split = input.split("(?=\\s+)", 2);

Complete demo:

List<String> inputs = Arrays.asList("a b C d", "a    b c d");
for (String input : inputs) {
    String[] split = input.split("(?=\\s+)", 2);
    for (String part : split) {
        System.out.format("Split string is '%s'%n", part);
    }
}

This prints:

Split string is 'a'
Split string is ' b C d'
Split string is 'a'
Split string is '    b c d'
Keppil
  • 45,603
  • 8
  • 97
  • 119
  • @mike for more information, and general idea behind your question: http://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters – Cruncher Mar 26 '14 at 15:49
0

try this

String[] a = s.split("(?<=^\\w+)\\s+");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
-1

You'll have to split using "\t" because \t is for a tab character. \s means any whitespace so it includes spaces.

Scott Shipp
  • 2,241
  • 1
  • 13
  • 20