5

If I had the following

str1 = "   Just a test   "
str2 = "                "

l1 = str1.strip().split()
l2 = str2.strip().split()

I'd get

l1 = ["Just", "a", "test"]
l2 = []

How would I accomplish this in Java?

Ryan Smith
  • 709
  • 1
  • 7
  • 14
  • 4
    Possible duplicate of [How to split a String by space](http://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space) – dazedconfused Oct 12 '15 at 02:15
  • 1
    If you start at the javadoc for String, you'd find the answer for yourself in *less* time than it takes to get the answer here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html – Andreas Oct 12 '15 at 02:19
  • Note for both answers that every call to `split` compiles a new regular expression object. For efficiency, compile it once in advance and place it in a `private static final` field. – Alex Hall Oct 12 '15 at 02:34

2 Answers2

3

You could use String.trim() and String.split(String) (which takes a regular expression). Something like,

String str1 = "   Just a test   ";
String str2 = "                ";
String[] l1 = str1.trim().split("\\s+");
String[] l2 = str2.trim().split("\\s+");
System.out.println(Arrays.toString(l1));
System.out.println(Arrays.toString(l2));

Outputs (the requested)

[Just, a, test]
[]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

You can use Java's trim() and split("\\s+") For example

String str1 = "   Just a test   ";
String[] toks = str1.trim().split("\\s+");

Then toks will be ["Just", "a", "test"]

0x56794E
  • 20,883
  • 13
  • 42
  • 58