获取字符串中的特定字符

时间:2014-12-05 19:35:12

标签: java android string

我有一个可以变化的字符串:

String filePath = "/this/is/my/file.txt";

我需要将此字符串转换为其他字符串信息:

"/this/is/my" and "file.txt"

我尝试了这种方法,但失败了(崩溃):

    int counter = 0;
    filePath = "/this/is/my/file.txt";
    String filePath2 = filePath.substring(filePath.lastIndexOf("/") + 1); // return "file.txt"
    for (int i = 0; i < filePath2.length(); i++) {
        counter++; // count number of char on filePath2
    }
    String filePath3 = filePath3.substring(filePath.lastIndexOf("") + counter); // Remove "file.txt" from filePath2 depending of character numbers on filePath2 backwards

任何人都知道更好的方法吗?谢谢!

12-05 15:53:00.940  11102-11102/br.fwax.paulo.flasher E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: br.fwax.paulo.flasher, PID: 11102
    java.lang.RuntimeException: Unable to start activity ComponentInfo{br.fwax.paulo.flasher/br.fwax.paulo.flasher.MFlasher}: java.lang.StringIndexOutOfBoundsException: length=21; index=29

3 个答案:

答案 0 :(得分:3)

Java的File类怎么样?

File f = new File(filePath);
String directory = f.getParent();
String fileName = f.getName();

答案 1 :(得分:3)

为什么你甚至有你的for循环?

int index = filePath.lastIndexOf("/");
String firstString = filePath.substring(0, index);
String secondString = filePath.substring(index+1, filePath.length());

答案 2 :(得分:1)

您可以使用File课程。

String filePath = "/this/is/my/file.txt";

File f = new File(filePath);

System.out.println(f.getParent());// \this\is\my
System.out.println(f.getName());// file.txt

请注意,这可以将/更改为\,但如果您要将此结果用作与文件相关的其他API中的参数,则此更改不应存在任何问题。

相关问题