Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String split

 
sankari subash
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

i have a string 1;2;3;;;4;;;
i want to split the string and put it in a list [1,2,3,,,4,,]

But while using the split method i found that the trailing blanks are eliminated.. please tell a solution for this
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do that with the "String.split(String regex,int limit)" method by using a negative value for the limit parameter.
 
Harish Tiruvile
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

Even you can try out using replace method...it works
FYI:
str = str.replace(";", ",");
 
Nalaka Gamage
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test1 {
public static void main(String[] args) {
String aa = "1;2;3;;;4;;;";
String bb = aa.replace(';',',');
String[] cc = bb.split(";");
java.util.List dd = Arrays.asList(cc);
System.out.println(dd);
}
}

Output:[1,2,3,,,4,,,]

Regards,
Nalaka
http://javatouch.googlepages.com
 
Dave Jones
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int limit = -1;
String[] cc = aa.split(";", limit);

Or limit should be the length of the reslut(slots) you want.

Read more in the API(look for the split method:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i'm not able to understand the program

when
String bb = aa.replace(';',',');
this happens, there is no such pattern as ';' in the string bb

so how can we split it based on this

String[] cc = bb.split(";");

and its working fine...

any light on this.
 
Henry Wong
author
Marshal
Pie
Posts: 21385
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by gaurav abbi:
hi,
i'm not able to understand the program

when
String bb = aa.replace(';',',');
this happens, there is no such pattern as ';' in the string bb

so how can we split it based on this

String[] cc = bb.split(";");

and its working fine...

any light on this.



Actually, it doesn't work. What is happening is that you simply changed the delimiter to a comma, which is the separator used by the List toString() method.

So you have one element that happens to have commas, and not nine elements, that is separated by commas.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic