I found a very strange problem in my java program. I want find indices of all pipe in my string and save them into 5 variables, but result is not right. Here is my program:
public class forTest {
public static void main(String[] args){
String tmp = "A|B|C|D|E|F|";
int count = 0;
int start = 0;
int start1 = 0;
int start2 = 0;
int start3 = 0;
int start4 = 0;
for(int i = 0; i < tmp.length(); i++){
if(tmp.substring(i, i+1).equals("|")){
count = count + 1;
System.out.println(i);
}
if(count == 1){
start = i;
}
if(count == 2){
start1 = i;
}
if(count == 3){
start2 = i;
}
if(count == 4){
start3 = i;
}
if(count == 5){
start4 = i;
}
}
System.out.println(start + "|" +start1 + "|" +start2
+ "|" +start3 + "|" +start4);
}
Output:
Result is 1
1 3 5 7 9 11
2|4|6|8|10
As you iterate, the first |
will increment count
to 1
, and set start = 1
, but on next iteration when you're positioned on the B
, the count is still 1, and start
is updated to 2
.
Debugging with a breakpoint on start = i;
would have let you see this for yourself!
Solution: Move all the if
statements inside the first one.
Also, tmp.substring(i, i+1).equals("|")
should be tmp.charAt(i) == '|'
, and use else if
.
for (int i = 0; i < tmp.length(); i++) {
if (tmp.charAt(i) == '|') {
count = count + 1;
System.out.println(i);
if (count == 1) {
start = i;
} else if (count == 2) {
start1 = i;
} else if (count == 3) {
start2 = i;
} else if (count == 4) {
start3 = i;
} else if (count == 5) {
start4 = i;
}
}
}
Alternate solutions
A shorter piece of code to get the same result can be done using a regular expression:
String tmp = "A|B|C|D|E|F|";
String regex = "(\\|).*?(\\|).*?(\\|).*?(\\|).*?(\\|)";
Matcher m = Pattern.compile(regex).matcher(tmp);
if (m.find()) {
int start = m.start(1);
int start1 = m.start(2);
int start2 = m.start(3);
int start3 = m.start(4);
int start4 = m.start(5);
System.out.println(start + "|" +start1 + "|" +start2 + "|" +start3 + "|" +start4);
}
Or if you don't like that, you could use an array:
String tmp = "A|B|C|D|E|F|";
int count = 0;
int[] start = new int[5];
for (int i = 0; i < tmp.length(); i++)
if (tmp.charAt(i) == '|' && count < start.length)
start[count++] = i;
System.out.println(start[0] + "|" +start[1] + "|" +start[2] + "|" +start[3] + "|" +start[4]);
Output (from both)
1|3|5|7|9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.