2016-07-27 101 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); 

这工作很细

相关问题