子字符串替换问题

And*_*eaF 0 java string android str-replace

我有一个可以假设两种形式的String

第一种形式

 file:///mnt/sdcard/myfolder/myfile.txt
Run Code Online (Sandbox Code Playgroud)

第二种形式

 /file://mnt/sdcard/myfolder/myfile.txt
Run Code Online (Sandbox Code Playgroud)

而且我总是需要表格中的字符串

/mnt/sdcard/myfolder/myfile.txt
Run Code Online (Sandbox Code Playgroud)

所以我使用了replace命令

myPath=path.replace("file://", "");
myPath= path.replace("/file:/", "");
Run Code Online (Sandbox Code Playgroud)

但不幸的是不起作用

和字符串myPath结果

file:///mnt/sdcard/myfolder/myfile.txt
Run Code Online (Sandbox Code Playgroud)

怎么了?

dre*_*nay 5

如果你保证你的字符串将始终是这两种形式之一,为什么不使用

myPath = path.substring(path.indexOf("/mnt"));
Run Code Online (Sandbox Code Playgroud)

如果你不确定你的路径是否包含"/ mnt",你可以试试这个:

if (path.contains("file:"))
{
    myPath = path.substring(path.indexOf(":/") + 1);
    while (myPath.startsWith("//"))
        myPath = myPath.substring(1);
}
Run Code Online (Sandbox Code Playgroud)