68

passing 0 as a limit argument prevents trailing empty strings, but how does one prevent leading empty strings?

for instance

String[] test = "/Test/Stuff".split("/");

results in an array with "", "Test", "Stuff".

Yeah, I know I could roll my own Tokenizer... but the API docs for StringTokenizer say

"StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split"

10 Answers 10

51

Your best bet is probably just to strip out any leading delimiter:

String input = "/Test/Stuff";
String[] test = input.replaceFirst("^/", "").split("/");

You can make it more generic by putting it in a method:

public String[] mySplit(final String input, final String delim)
{
    return input.replaceFirst("^" + delim, "").split(delim);
}

String[] test = mySplit("/Test/Stuff", "/");
Sign up to request clarification or add additional context in comments.

Comments

23

Apache Commons has a utility method for exactly this: org.apache.commons.lang.StringUtils.split

StringUtils.split()

Actually in our company we now prefer using this method for splitting in all our projects.

2 Comments

Seems to don't support regular expression like the JDK version though.
It causes issue when you have multi-character seperator like - ##. for ex: String str = "lorem##ipsum#dolor"; String[] split = StringUtils.split(str, "##"); It results in ["lorem", "ipsum", "dolor"]
5

I don't think there is a way you could do this with the built-in split method. So you have two options:

1) Make your own split

2) Iterate through the array after calling split and remove empty elements

If you make your own split you can just combine these two options

public List<String> split(String inString)
{
   List<String> outList = new ArrayList<>();
   String[]     test    = inString.split("/");

   for(String s : test)
   {
       if(s != null && s.length() > 0)
           outList.add(s);
   }

   return outList;
}

or you could just check for the delimiter being in the first position before you call split and ignore the first character if it does:

String   delimiter       = "/";
String   delimitedString = "/Test/Stuff";
String[] test;

if(delimitedString.startsWith(delimiter)){
    //start at the 1st character not the 0th
    test = delimitedString.substring(1).split(delimiter); 
}
else
    test = delimitedString.split(delimiter);

Comments

2

I think you shall have to manually remove the first empty string. A simple way to do that is this -

  String string, subString;
  int index;
  String[] test;

  string = "/Test/Stuff";
  index  = string.indexOf("/");
  subString = string.substring(index+1);

  test = subString.split("/"); 

This will exclude the leading empty string.

2 Comments

But with this code, if an input string didn't have a leading delimiter, you'd skip the first component. For example, "Test/Stuff" would yield just a single element, "Stuff".
Good point. In that case, an additional check would have to be made.
1

I think there is no built-in function to remove blank string in Java. You can eliminate blank deleting string but it may lead to error. For safe you can do this by writing small piece of code as follow:

  List<String> list = new ArrayList<String>();

  for(String str : test) 
  {
     if(str != null && str.length() > 0) 
     {
         list.add(str);
     }
  }

  test = stringList.toArray(new String[list.size()]);

Comments

1

When using JDK8 and streams, just add a skip(1) after the split. Following sniped decodes a (very wired) hex encoded string.

Arrays.asList("\\x42\\x41\\x53\\x45\\x36\\x34".split("\\\\x"))
    .stream()
    .skip(1) // <- ignore the first empty element
    .map(c->""+(char)Integer.parseInt(c, 16))
    .collect(Collectors.joining())

Comments

1

Split method variants like split(regex, limit) can also produce empty strings at beginning or in middle of the resulting String array. Below code removes all such empty strings using streams api filter method in Java 8.

Sample code:

String[] tokens = s.split("/");
Arrays.stream(tokens)
.filter(s1 -> !s1.isEmpty())
.forEach(System.out::println);

Comments

0

You can use StringTokenizer for this purpose...

String test1 = "/Test/Stuff";
        StringTokenizer st = new StringTokenizer(test1,"/");
        while(st.hasMoreTokens())
            System.out.println(st.nextToken());

7 Comments

StringTokenizer is marked as deprecated in the API and probably shouldn't be used.
@McMillen can you please say from which version it is got deprecated. Actually I don't know this.
It's not officially deprecated, but the Javadocs state "StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead."
@ShashankKadne It may not say deprecated but there is this exact line in the API page: StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
|
0

This is how I've gotten around this problem. I take the string, call .toCharArray() on it to split it into an array of chars, and then loop through that array and add it to my String list (wrapping each char with String.valueOf). I imagine there's some performance tradeoff but it seems like a readable solution. Hope this helps!

 char[] stringChars = string.toCharArray(); 
 List<String> stringList = new ArrayList<>(); 

 for (char stringChar : stringChars) { 
      stringList.add(String.valueOf(stringChar)); 
 }

Comments

-2

You can only add statement like if(StringUtils.isEmpty(string)) continue; before print the string. My JDK version 1.8, no Blank will be printed. 5 this program gives me problems

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.