2011-04-27 131 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