wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in split() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in split()" Watch "Doubt in split()" New topic
Author

Doubt in split()

cfish meena
Greenhorn

Joined: Apr 05, 2007
Posts: 19
Can anyone please help me to undertsand why the output of the program is 4.

public class splitTry {
public static void main(String[] args) {
String str="aaaaaaaaabb";
String[] s=str.split("a{3}");
System.out.println(s.length);
}
}
mallika arora
Greenhorn

Joined: Aug 02, 2007
Posts: 5
String str="aaaaaaaaabb";

When you split the above string using the given crieria(alpha numeric character at every 3rd position), it splits the String like this: "aaa", "aaa","aaa","bb"

and stores it in array at 0,1,2,3 index so the length is 4.
Neha Bhattad
Ranch Hand

Joined: Aug 20, 2007
Posts: 30
String = "boo:and:foo"
Calling String.split() with following regex:

RegexResult
:{ "boo", "and", "foo" }
o{ "b", "", ":and:f" }

When regex is "o" an empty string is created when "oo" is found in boo. Why is an empty string not found when the String splits on the last two "oo"??
In other words y is the array length 3 and not 4 with two empty strings?
sharathchandra edupuganti
Greenhorn

Joined: Aug 21, 2007
Posts: 2
When you call the split function with only one argument ,then it assumes that the second argument of the split function is zero. And when the second argument is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. This is the reason why you are not seeing the trailing empty strings.
Roland Schneider
Greenhorn

Joined: Sep 19, 2007
Posts: 12
@mallika arora:
The array contains after the split [, , , bb] so the length is 4.
[ October 10, 2007: Message edited by: Roland Schneider ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in split()
 
Similar Threads
how to reduce the number of input parameters to a java function?
Navigation does not work
Getting simple JBoss Seam sample to work
jsp
Enum Naming Convention