Java 如何删除每行中的最后一个组
如果我有这组行:Java 如何删除每行中的最后一个组,java,for-loop,indexing,charat,Java,For Loop,Indexing,Charat,如果我有这组行: 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 我想删除最后一个空格后的最后一个组。 我有这样的代码,但它不起作用,所以我需要帮助: for(int i=0;i<=lines.length-1; i++){ // get i
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
我想删除最后一个空格
后的最后一个组。
我有这样的代码,但它不起作用,所以我需要帮助:
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);
}
import java.util.*;
导入java.lang.*;
导入java.io.*;
表意文字
{
公共静态void main(字符串[]args)引发java.lang.Exception
{
字符串[]输入=新字符串[2];
输入[0]=“812.12 135.14 646.17 1”;
输入[1]=“812.12 135.14 646.21 100”;
字符串s;
int x;
对于(int i=0;iDefine“它不起作用”。发布一个完整的最小示例,再现该问题,并说明实际输出是什么,预期输出是什么。您能解释为什么第一行后面有一个“1”吗最后?它不应该被移除吗?对于你想要的,它工作正常。你能分享你得到的输出吗。问题一定在其他地方
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
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]);
}
}