Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Python's str.strip().split()?

Tags:

java

python

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?

like image 914
Ryan Smith Avatar asked Oct 12 '15 02:10

Ryan Smith


People also ask

How do you split a string in Java?

Split() String method in Java with examples. The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.

What is split () in Python?

Definition and Usage. The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

What is the difference between Split and strip in Python?

There's no difference. split() ignores whitespace on the ends of the input by default. People call strip() first either because they think it's clearer or because they don't know this behavior of split() .


1 Answers

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]
[]
like image 190
Elliott Frisch Avatar answered Sep 28 '22 04:09

Elliott Frisch