• Post Reply Bookmark Topic Watch Topic
  • New Topic

split string using "|"  RSS feed

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a string like this:

String str="1|5202558|1|562548|9|24937";
i need to split this string with "|" and put those value in map like this:

1|5202558
1|562548
9|24937

String str="1|5202558|1|562548|9|24937"
roleUnitPairs = str.split("\\|");
for(int i=0;i<roleUnitPairs.length;i++){
unitMap.put(roleUnitPairs[0], roleUnitPairs[1]);
}
but this will always result in
1|5202558

can any one get me out of this issue???
 
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should be using the value of "i" instead of always using "0" and "1".

And you need to increment i by 2 at each loop iteration, not 1.
 
Nag Venkat
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sory iam getting array indexoutof bond excption..then i tried like this:


String str="1|5202558|1|562548|9|24937";
String oleUnitPairs[] = str.split("\\|");

for(int i=0;i<oleUnitPairs.length;i++){
if (i % 2 != 0) {
unitMap.put(oleUnitPairs[i], oleUnitPairs[i++]);
}
}
System.out.println(unitMap);

now iam getting output as:
{24937=24937, 562548=562548, 5202558=5202558}

but i need to get it as

{9=24937, 1=562548, 1=5202558}
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"i++" is not the same as "i+1" - which is what you should be using.

And you need to increment i by 2 at each loop iteration, not 1.


... instead of the "i % 2" construct.
 
Nag Venkat
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you mean :

for(int i=0;i<oleUnitPairs.length;i=i+2){

unitMap.put(oleUnitPairs[i], oleUnitPairs[i++]);
}
 
Bartender
Posts: 1166
17
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no need for any post processing after the split. You can use

which splits at '|' when followed by a single decimal digit followed by another '|' .

Edit : Having re-read the OP I think I have misread it!
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hitendra sunkara wrote:you mean :

for(int i=0;i<oleUnitPairs.length;i=i+2){

unitMap.put(oleUnitPairs[i], oleUnitPairs[i++]);
}


Not quite:
"i++" is not the same as "i+1" - which is what you should be using.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!