Reputation: 6653
I'm trying to separate / explode an String to do something with it later on.
The input string is this:
1_2_3_2_2
The function I'm calling with the above value as parameter:
void parseXString(String value){
int amountX = (value.length() / 2) + 1;
int seperatorIndex = value.indexOf('_');
int secondSeperator = 0;
for(int i = 0; i < amountX; i++){
String xPoint = "";
if(i == 0){
xPoint = value.substring(0, seperatorIndex);
}else{
xPoint = value.substring(seperatorIndex + 1, secondSeperator);
}
sendMessage((String)i + " X = " + xPoint + " || SEP: " + (String)seperatorIndex + " / " + (String)secondSeperator );
seperatorIndex = value.indexOf("_", seperatorIndex + 1);
secondSeperator = value.indexOf("_", seperatorIndex + 1);
}
sendMessage("Last X = " + value.substring(seperatorIndex + 1));
}
The sendMessage
function will shout the value back to the operating Java application. The output I get is this:
0 X = 1 || SEP: 1 / 0
1 X = 3 || SEP: 3 / 5
2 X = 2 || SEP: 5 / 7
3 X = 2 || SEP: 7 / -1
4 X = 1 || SEP: -1 / 1
Last X = 2_3_2_2
As you can notice, on the second iteration there should be an return of the value 2
instead of an 3
.
I think there's something wrong with the seperatorIndexes
, but I'm out of the blank right now (working on this way to long).
So my question is very simple. Why doesn't I get the right value back / how can I fix that?
Upvotes: 1
Views: 169
Reputation: 802
Your error is that you increase seperatorIndex
in the first iteration. Therefore, seperatorIndex
is 3 in your second iteration.
You should put the part where you increment seperatorIndex
into the else part of your if(i == 0)
condition. When doing this, you also have to increment secondSeperator
in the if part of your condition.
Upvotes: 2