0

我正在尝试用字符串内的缩短 URL 替换 URL:

public void shortenMessage()
    {
        String body = composeEditText.getText().toString();
        String shortenedBody = new String();
        String [] tokens = body.split("\\s");

        // Attempt to convert each item into an URL.  
        for( String token : tokens ) 
        {
            try
            {
                Url url = as("mycompany", "someapikey").call(shorten(token));
                Log.d("SHORTENED", token + " was shortened!");
                shortenedBody = body.replace(token, url.getShortUrl());
            }
            catch(BitlyException e)
            {
                //Log.d("BitlyException", token + " could not be shortened!");

            }
        }

        composeEditText.setText(shortenedBody);
        // url.getShortUrl() -> http://bit.ly/fB05
    }

缩短链接后,我想在 EditText 中打印修改后的字符串。我的 EditText 没有正确显示我的消息。

例如:

"I like www.google.com" should be "I like [some shortened url]" after my code executes.
4

2 回答 2

3

在 Java 中,字符串是不可变的。String.replace() 返回一个新字符串,它是替换的结果。因此,当您shortenedBody = body.replace(token, url.getShortUrl());在循环中执行时,shortenedBody将保存(仅)最后一次替换的结果。

这是一个修复,使用 StringBuilder。

public void shortenMessage()
{
    String body = composeEditText.getText().toString();
    StringBuilder shortenedBody = new StringBuilder();
    String [] tokens = body.split("\\s");

    // Attempt to convert each item into an URL.  
    for( String token : tokens ) 
    {
        try
        {
            Url url = as("mycompany", "someapikey").call(shorten(token));
            Log.d("SHORTENED", token + " was shortened!");
            shortenedBody.append(url.getShortUrl()).append(" ");
        }
        catch(BitlyException e)
        {
            //Log.d("BitlyException", token + " could not be shortened!");

        }
    }

    composeEditText.setText(shortenedBody.toString());
    // url.getShortUrl() -> http://bit.ly/fB05
}
于 2011-04-27T17:09:58.293 回答
-1

您可能希望String.replaceAllPattern.quote在将字符串传递给需要正则表达式的 replaceAll 之前“引用”您的字符串。

于 2011-04-27T17:29:46.660 回答