Bala
Bala

Reputation: 11264

How to split string, remove last element and join back in Java?

I have a array variable filesFound that holds a filename. How do I go about removing the last number part including its extension.

...
File[] filesFound = SomeUtils.findFile("xyz","c:\\") 

//fileFound[0] is now "abc_xyz_pqr_27062016.csv"
//What I need is "abc_xyz_pqr" only

String[] t = filesFound[0].toString().split("_")
Arrays.copyOf(t, t.length - 1) //this is not working
...

Upvotes: 9

Views: 18737

Answers (6)

Naghaveer R
Naghaveer R

Reputation: 2944

If you're using JAVA 8 or above, you can use .limit and Collector.joining()

    String someString = "abc_xyz_pqr_27062016.csv";
    String[] splitArray = searchTerm.split("_");
    
    //Limiting the array length, not to consider last element while joining
    String stringAfterJoining = Arrays.stream(splitArray)
            .limit(splitArray.length - 1)
            .collect(Collectors.joining("_"));

Upvotes: 1

Hatley
Hatley

Reputation: 259

How about .substring() & .lastIndexOf()?

String file = filesFound[0];
String newFileName = file.substring(0, file.lastIndexOf("_"));

the newFileName would then contain everything up to (but not including) the last '_' char.

Upvotes: 10

Young Emil
Young Emil

Reputation: 2276

In a bit stress way..

            //fileFound[0] is now "abc_xyz_pqr_27062016.csv"

            String file = fileFound[0] ;
            String filter = "";
            int i = 0;
            char [] allChars = file.toCharArray();
            char oneChar ;
            while(i < (file.length()-4)){//4 is .csv
                oneChar = allChars[i];
                if((oneChar >= 65 && oneChar <=90)||(oneChar >= 97 && oneChar <=122)|| oneChar==95){
                    filter += oneChar;
                }
                i++;

            }
            filter = filter.substring(0, filter.length()-1);
            System.out.println(filter);

This works very fine

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37604

Regex:

System.out.println("abc_xyz_pqr_27062016.csv");       

System.out.println("abc_xyz_pqr_27062016.csv".replaceAll("_\\d+.+",""));

Prints out:

abc_xyz_pqr_27062016.csv
abc_xyz_pqr

Upvotes: 2

bradimus
bradimus

Reputation: 2523

Copying the array will not concatenate the parts back together. Try

StringBuilder builder = new StringBuilder();
for (int i = 0; i < t.length - 1; i++) {
    builder.append(t[i]);
}
String joined = builder.toString();

Upvotes: 6

Jens
Jens

Reputation: 69460

Arrays.copyOf returns a new array, so you have to assign it to t or a new variable:

t = Arrays.copyOf(t, t.length - 1)

Upvotes: 6

Related Questions