java中的变量参数
我有以下课程:java中的变量参数,java,string,variadic-functions,Java,String,Variadic Functions,我有以下课程: public class WhereSqlClause{ public static String build(String pattern, Object... args){ //For instance, pattern = "Some string :placeholder" //and we call this method as WhereSqlClause.build(pattern, placeholder)
public class WhereSqlClause{
public static String build(String pattern, Object... args){
//For instance, pattern = "Some string :placeholder"
//and we call this method as WhereSqlClause.build(pattern, placeholder)
//where placeholder was a local variable initialized before
}
}
我的问题是如何用占位符.toString()
值替换所有占位符,如:占位符
例如:
String pattern = "Some str another str:place :holder";
Object place = "Place";
Object holder = "Holder";
String WhereSqlClause.build(pattern, place, holder);
//Have to produce "Some str Place another str Holder"
及
一个字符串的示例,在您只需迭代参数之后
//For instance, pattern = "Some string :placeholder"
//and we call this method as WhereSqlClause.build(pattern, placeholder)
//where placeholder was a local variable initialized before
StringBuilder sbPattern = new StringBuilder();
sbPattern.append(pattern);
// you get ":placeholder "
String placeholder = ":"+(String)args[0].toLowerCase() + " ";
// if is in the pattern, replace it
if (pattern.contains(placeholder)) {
int i = pattern.indexOf(placeholder);
sbPattern.replace(i, i + placeholder.length() , (String)args[0] + " ");
}
您可以使用MessageFormat,它可以根据占位符的位置替换占位符 您需要表单的模式:
"some template with param {0} and another param {1}"
然后你可以写:
public static String build (String pattern, Object... args)
{
MessageFormat formatter = new MessageFormat (pattern);
StringBuffer output = new StringBuffer (256);
return formatter.format (args, output, null).toString();
}
试过连接吗?@Stultuske你没有;我不明白。我想知道如何使用局部变量的名称。@St.Antario这不是类型安全的。@Pshemo我不是。请看第二个例子,“我想知道如何使用局部变量的名称。”这是不可能的。Java不按名称使用变量,而是按地址使用变量。如果要存储一些
name->value
对,请使用Map
而不是varargs。字符串是不可变的。即使它们是可变的,如果占位符是:foo
和:fooBar
?用value替换:foo
,我们也将得到值栏
。@Pshemo同意。。。请稍等片刻,等待修复。。。。关于:foobar
不。。。。“阅读我的代码…”关于:foobar不…阅读我的代码…”确定不会,因为您正在占位符的末尾添加空格,但如果占位符将放置在模式的末尾,并且在其后面没有空格,则此解决方案存在问题。只要OP创建了模式,我想这是一个OP可以遵循的规则,以避免问题和一个简单的解决方案,以适应需要…嗯。。。我需要替换作为参数传递的名为place
的变量/字段的占位符,如:place
。你是如何看待这个案子的?@St.Antario我认为你的确切要求是不可能的。至少在varags中是不可用的(变量的名称在方法中是不可用的),所以我建议做一些类似的事情,这样做很容易。另一种方法是传递带有占位符名称及其各自值的映射
,这将允许您在模式字符串中搜索并替换它们。
public static String build (String pattern, Object... args)
{
MessageFormat formatter = new MessageFormat (pattern);
StringBuffer output = new StringBuffer (256);
return formatter.format (args, output, null).toString();
}
String[] myArgs = {"arg1", "arg2"};
String sentence = "here is a text with :arg and :arg";
int counter = 0;
while (sentence.indexOf(":arg") != -1) {
sentence = sentence.substring(0, sentence.indexOf(":arg")) + myArgs [counter] + sentence.substring(sentence.indexOf(":arg") + 4, sentence.length());
counter++;
}