aspose file tools*
The moose likes Java in General and the fly likes String split method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "String split method " Watch "String split method " New topic
Author

String split method

Christian Lombardo
Greenhorn

Joined: May 28, 2009
Posts: 10
I am working on a simple Java code and cannot seem to understand why the empty string (in the String tokens array) is not detected by the if statement, see below for the code:

public class SplitTest {

public static void main( String[] args )
{
String data = "Hello,,I am me, DO IT,NOW,yeah MON!,,,,,5,";
String[] tokens = data.split("\\,");
for (int element = 0; element < 11 ; element ++) {
System.out.print(">");
System.out.print(tokens[element]);
System.out.println("<");

if (tokens[element] == "")
System.out.print(" Empty String here");

if (tokens[element] == null)
System.out.print(" NULL here");
}
}
}
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18702
    
  40

It may be a good idea to read the Javadoc... The default split() method truncates trailing zero length matches.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Christian Lombardo
Greenhorn

Joined: May 28, 2009
Posts: 10
I do not understand. When you run the code it prints an empty string.

The Javadoc: http://java.sun.com/javase/6/docs/api/ does not explain details of the split() method in regards to empty strings.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18702
    
  40

Also, when you do string comparison, use the equals() method -- the == operator is for references comparison only.

Henry
Christian Lombardo
Greenhorn

Joined: May 28, 2009
Posts: 10
Thank you Henry.
Manish Singh
Ranch Hand

Joined: Jan 26, 2007
Posts: 160
And instead of doing

for (int element = 0; element < 11 ; element ++) {

use the .length property of the arrays
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String split method