如果我有这组线:
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
我想在最后一个space
之后删除最后一组,我该怎么办呢。
我有这样的代码,但它没有用,所以我需要帮助:
for(int i=0;i<=lines.length-1; 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);
}
结果应该是这样的:
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
答案 0 :(得分:0)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String[] input=new String[2];
input[0]="812.12 135.14 646.17 1";
input[1]="812.12 135.14 646.21 100";
String s;
int x;
for(int i=0;i<input.length;i++)
{
s=input[i];
x=s.length();
x=x-1;
while(s.charAt(x)!=' ') /*Iterated from the last character of the string till we get a space*/
x--;
s=s.substring(0,x); /*Used the index of last space from above to cut out a substring from 0th index till the index of last space*/
input[i]=s;
}
System.out.println(input[0]+"\n"+input[1]);
}
}
以下是您想要的工作演示。我已经在评论中解释了代码,请阅读它以理解代码。