programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# split string using "|"

Ranch Hand
Posts: 43
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
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
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
"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
you mean :

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

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

Bartender
Posts: 1166
17
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
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.