如何在每个String索引中连接字符串或单词

时间:2014-02-04 09:07:32

标签: java android encoding string-concatenation url-encoding

我无法使用非ASCII和空格组合编码网址。例如,http://xxx.xx.xx.xx/resources/upload/pdf/APPLE ははは.pdf。我已阅读here,您只需要对网址路径的最后部分进行编码。

以下是代码:

public static String getLastPathFromUrl(String url) {
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}

所以现在我已经APPLE ははは.pdf,下一步是用%20替换空格以使链接生效但是问题是如果我编码{{1}它变为APPLE%20ははは.pdf我应该 APPLE%2520%E3%81%AF%E3%81%AF%E3%81%AF.pdf

所以我决定:

APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf

这是我的代码:

1. Separate each word from the link
2. Encode it
3. Concatenate the new encoded words, for example:
    3.A. APPLE (APPLE)
    3.B. %E3%81%AF%E3%81%AF%E3%81%AF.pdf (ははは.pdf)
    with the (space) converted to %20, now becomes APPLE%20%E3%81%AF%E3%81%AF%E3%81%AF.pdf

主叫代码:

public static String[] splitWords(String sentence) {
    String[] words = sentence.split(" ");
    return words;
}

我现在想要在索引中连接每个单字节的字符串(String urlLastPath = getLastPathFromUrl(pdfUrl); String[] splitWords = splitWords(urlLastPath); for (String word : splitWords) { String urlEncoded = URLEncoder.encode(word, "utf-8"); //STUCKED HERE } ),最终形成类似urlEncoded的形式。我该怎么做?

4 个答案:

答案 0 :(得分:1)

实际上%20被编码为%2520所以只需调用URLEncoder.encode(word,“utf-8”);所以你会得到这样的结果APPLE +%E3%81%AF%E3%81%AF%E3%81%AF.pdf和最终结果替换+%20。

答案 1 :(得分:1)

你想做这样的事情:

// Get the whole url as string
Stirng urlString = pdfUrl.toString();

// get the string before the last path segment
String result = urlString.substring(0, urlString.lastIndexOf("/"));

String urlLastPath = getLastPathFromUrl(pdfUrl);
String[] splitWords = splitWords(urlLastPath);

for (String word : splitWords) {
    String urlEncoded = URLEncoder.encode(word, "utf-8");

    // add the encoded part to the url
    result += urlEncoded;
}

现在字符串result是您编码的URL作为字符串。

答案 2 :(得分:1)

org.apache.commons.io.FilenameUtils可能很容易。

  1. 将您的网址拆分为baseUrlfile name and extension
  2. file name and extension
  3. 进行编码
  4. 加入他们
  5. String url = "http://xxx.xx.xx.xx/resources/upload/pdf/APPLE ははは.pdf";

    String baseUrl = FilenameUtils.getPath(url); // GIVES: http://xxx.xx.xx.xx/resources/upload/pdf/
    String myFile = FilenameUtils.getBaseName(url)
                + "." + FilenameUtils.getExtension(url); // GIVES: APPLE ははは.pdf
    String encoded = URLEncoder.encode(myFile, "UTF-8"); //GIVES: APPLE+%E3%81%AF%E3%81%AF%E3%81%AF.pdf
    System.out.println(baseUrl + encoded);
    

    <强>输出:

    http://xxx.xx.xx.xx/resources/upload/pdf/APPLE+%E3%81%AF%E3%81%AF%E3%81%AF.pdf
    

答案 3 :(得分:0)

不要重新发明轮子。使用URLEncoder对URL进行编码。

URLEncoder.encode(yourArgumentsHere, "utf-8");

此外,您从哪里获取URL,以便在编码之前必须将其拆分?您应该首先构建参数(最后一部分),然后将其附加到基本URL。