-3

If i have this group of 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 the last group after the last space how can I do it. I had code like this but it didn't work so I need help:

 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);
}

The result should be like that:

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 
Dany
  • 37
  • 1
  • 2
  • 8
  • 3
    Define "it didn't work". Post a complete minimal example reproducing the issue, and tell what the actual output is, and what the expected output is. – JB Nizet Nov 14 '17 at 07:06
  • 3
    Can you explain why the first line has a trailing "1" at the end? Shouldn't it have been removed? – Mureinik Nov 14 '17 at 07:06
  • 3
    It work's fine, for what you intend to. Can you share what output you are getting. problem must be somewhere else – Tejendra Nov 14 '17 at 07:06

1 Answers1

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]);


    }
}

Here is the working demo of what you wanted. I have explained the code in comments, please read it to understand the code.

anupam691997
  • 310
  • 2
  • 8