ReplaceAll 不替换字符串
我希望将文本“REPLACEME”替换为我的 StringBuffer 符号。当我打印符号时,它是一个有效的字符串。当我打印查询时,它仍然具有文本 REPLACEME 而不是符号。为什么?
private String buildQuery(){
String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
deserializeQuotes();
StringBuffer symbols = new StringBuffer();
for(int i = 0; i < quotes.size();i++){
if(i == (quotes.size()-1))
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
else
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
}
System.out.println("***SYMBOLS***" + symbols.toString());
query.replaceAll("REPLACEME", symbols.toString());
return query;
}
I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?
private String buildQuery(){
String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
deserializeQuotes();
StringBuffer symbols = new StringBuffer();
for(int i = 0; i < quotes.size();i++){
if(i == (quotes.size()-1))
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
else
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
}
System.out.println("***SYMBOLS***" + symbols.toString());
query.replaceAll("REPLACEME", symbols.toString());
return query;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更改
为:
Java 中的字符串被设计为不可变。
这就是为什么
replaceAll()
无法替换当前字符串中的字符,因此它必须返回一个替换了字符的新字符串。另外,如果您想简单地替换文字并且不需要正则表达式语法支持,请使用
replace
而不是replaceAll
(正则表达式语法支持只是这两种方法之间的区别)。如果您想要替换可能包含正则表达式元字符的文字,例如*
、+
、[
、] 以及其他。
Change
to:
Strings in Java are designed to be immutable.
That is why
replaceAll()
can't replace the characters in the current string, so it must return a new string with the characters replaced.Also if you want to simply replace literals and don't need regex syntax support use
replace
instead ofreplaceAll
(regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like*
,+
,[
,]
and others.阅读文档:)replaceAll() 返回一个新的字符串,它会替换现有的字符串。原因是字符串是不可变的对象。
Read the documentation :) replaceAll() returns a new String, it does replace inside the existing String. The reason for that is that Strings are immutable objects.
Java中的String对象是不可变的。 ReplaceAll不会替换字符串中的数据,而是生成一个新的字符串。试试这个:
The String object in Java is immutable. The replaceAll will not replace the data in the string, it will generate a new string. Try this: