问题
I have this lines:
812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 10
812.12 135.14 646.20 10
812.12 135.14 646.21 100
812.12 135.14 646.22 100
I want to delete only the last group so I did code like this:
if(lines[i].charAt(lines[i].length())-1>= '0'&&lines[i].charAt(lines[i].length()-1)<= '9'){
lines[i] = lines[i].substring(0, lines[i].length()-1);
}
else if(lines[i].charAt(lines[i].length())>='10'+c&&lines[i].charAt(lines[i].length()-1)<='99'){
lines[i] = lines[i].substring(0, lines[i].length()-2);
}
else if(lines[i].charAt(lines[i].length())>='100'&&lines[i].charAt(lines[i].length()-1)<='999){
lines[i] = lines[i].substring(0, lines[i].length()-3);
}
And it's now working for me I need help please
回答1:
It isn't working it says a wrong on this line:
lines[i] = lines[i].substring(0, index);
@Everyone
回答2:
You have characters and trying to compare them as numbers. It doesn't work that way.
A char
in most higher-level (Java, .NET languages...etc) programming languages follows UTF-16
format by default. Since each char
size is 2 bytes
it can follow any encoding you need.
You cannot compare a char
to string
and you cannot attempt to put string in char like '10'
. Those are two characters, not one, it's a string
.
Now based on your desired output, you would like to remove everything after the last space. To do that, you can use the following code:
static void updateLines(String[] lines){
for(int i=0;i<lines.length; i++){
// get index of the last space
int index = lines[i].lastIndexOf(" ");
// remove everything after the last space
lines[i] = lines[i].substring(0, index);
}
}
public static void main(String[] args) {
String[] lines = new String[]{
"812.12 135.14 646.17 1",
"812.12 135.14 646.18 1",
"812.12 135.14 646.19 10",
"812.12 135.14 646.20 10",
"812.12 135.14 646.21 100",
"812.12 135.14 646.22 100",
"812.12 135.14 646.23 1000",
"812.12 135.14 646.24 1000"
};
updateLines(lines);
for(int i=0;i<lines.length;i++)
System.out.println(lines[i]);
}
Output:
812.12 135.14 646.17
812.12 135.14 646.18
812.12 135.14 646.19
812.12 135.14 646.20
812.12 135.14 646.21
812.12 135.14 646.22
812.12 135.14 646.23
812.12 135.14 646.24
Is this enough or do you need to compare numbers?
来源:https://stackoverflow.com/questions/47273979/how-to-check-2-charati