2016-07-27 103 views
0

我有一個包含文件名的數組變量filesFound。我如何去除最後的數字部分,包括其擴展名。如何拆分字符串,刪除最後一個元素並返回到Java?

... 
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 
... 
+0

拿什麼不工作? – Jens

回答

3

Arrays.copyOf返回一個新的數組,所以你必須將它指定T或一個新的變量:

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

@Downvoter請解釋 – Jens

3

複製陣列的部件不會串連到一起。嘗試

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

如何.substring() & .lastIndexOf()

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

newFileName隨後將包含一切達(但不包括)最後的「_」字符。

+0

「-1」是錯誤的。它應該是substring(0,file.lastIndexof('_')); – FredK

+0

@FredK - 你說得對,在'substring()'上升到但不包括第二個索引值,所以-1不是必需的。 **但是**我仍然喜歡這個簡短的一些迄今爲止提供的其他答案,並刪除-1使代碼更少=),所以我刪除它。順便趕上! – Hatley

2

正則表達式:

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

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

打印出:

abc_xyz_pqr_27062016.csv 
abc_xyz_pqr 
0

在有點壓力的方式..

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

這工作很細

相關問題