在 Java 中替换字符串时出现问题
我正在尝试用字符串内的缩短的 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.
I am trying to replace a URL with a shortened URL inside of a String:
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
}
After the links are shortened, I want to print the modified string in an EditText. My EditText is not displaying my messages properly.
For example:
"I like www.google.com" should be "I like [some shortened url]" after my code executes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Java 中,字符串是不可变的。 String.replace() 返回一个新字符串,它是替换的结果。因此,当您在循环中执行
shortenedBody = body.replace(token, url.getShortUrl());
时,shortenedBody
将保存(仅是最后一个)的结果代替。这是使用 StringBuilder 的修复方法。
In Java, strings are immutable. String.replace() returns a new string which is the result of the replacement. Thus, when you do
shortenedBody = body.replace(token, url.getShortUrl());
in a loop,shortenedBody
will hold the result of (only the very) last replace.Here's a fix, using StringBuilder.
您可能需要 String.replaceAll 和 Pattern.quote 在将字符串传递给需要正则表达式的replaceAll 之前“引用”该字符串。
You'll probably want String.replaceAll and Pattern.quote to "quote" your string before you pass it to replaceAll, which expects a regex.