2011-04-27 48 views
0

替換字符串我試圖用一個縮短的URL替換字符串內的URL:問題在Java中

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. 
+0

什麼打印到EditText? – Haphazard 2011-04-27 17:11:07

回答

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 
} 
+0

謝謝。這是很大的進步。縮短的URL顯示在EditText中,但字符串的其餘部分未被打印。例如:「我喜歡www.google.com」只會打印縮短的網址。我如何打印「我喜歡[縮短網址]」? – 2011-04-27 17:15:40

-1

你可能想String.replaceAllPattern.quote到「引用」你的字符串,你把它傳遞給的replaceAll,它接受一個正則表達式之前。

+0

無關緊要;在任何地方都沒有「replaceAll」的問題 – user102008 2011-06-20 09:50:43