在Java中替换String时出现问题

时间:2011-04-27 17:05:28

标签: java android string android-edittext bit.ly

我正在尝试用String中的缩短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.

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:-1)

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