Java String没有被替换

时间:2015-05-28 16:08:49

标签: java

我已经制作了这个小脚本来测试一些东西,但是我无法让它运行起来。 我希望它取代"%20"在字符串中" &#34 ;. 打印出来:Ravenous%20Cache.zip

package test;

public class Test {

    public static void main(String[] args) {
        System.out.println(getArchivedName());
    }

    private static String cacheLink = "https://dl.dropboxusercontent.com/u/Ravenous%20Cache.zip";

    private static String getCacheLink() {
        return cacheLink;
    }

    private static String getArchivedName() {
        String name = cacheLink.replace("%20", " ");
        int lastSlashIndex = name.lastIndexOf('/');
        if (lastSlashIndex >= 0 
            && lastSlashIndex < getCacheLink().length() -1) { 
            return getCacheLink().substring(lastSlashIndex + 1);
        } else {
            System.err.println("Error Downloading Game Files.");
        }
        return "";
    }

}

3 个答案:

答案 0 :(得分:2)

当您获取返回原始字符串的子字符串时,您再次调用getCacheLink()

return name.substring(lastSlashIndex + 1);

答案 1 :(得分:0)

试试这个:

public static void main(String[] args) {
        System.out.println(getArchivedName());
    }

    private static String cacheLink = "https://dl.dropboxusercontent.com/u/Ravenous%20Cache.zip";

    private static String getCacheLink() {
        return cacheLink;
    }

    private static String getArchivedName() {
        String name = cacheLink.replace("%20", " ");
        int lastSlashIndex = name.lastIndexOf('/');
        if (lastSlashIndex >= 0 
            && lastSlashIndex < getCacheLink().length() -1) { 
            return name.substring(lastSlashIndex + 1);//Changed
        } else {
            System.err.println("Error Downloading Game Files.");
        }
        return "";
    }

您正在返回getCacheLink()而不是name

答案 2 :(得分:0)

public class Test {

    public static void main(String[] args) {
        System.out.println(getArchivedName());
    }

    private static String cacheLink = "https://dl.dropboxusercontent.com/u/Ravenous%20Cache.zip";

    private static String getCacheLink() {
        return cacheLink;
    }

    private static String getArchivedName() {
        cacheLink = cacheLink.replace("%20", " ");
        int lastSlashIndex = cacheLink.lastIndexOf('/');
        if (lastSlashIndex >= 0 && lastSlashIndex < getCacheLink().length() - 1) {
            return getCacheLink().substring(lastSlashIndex + 1);
        } else {
            System.err.println("Error Downloading Game Files.");
        }
        return "";
    }
}