如何使用replace()
用Java中的不同字符串替换字符串的3个相同字符。
final String QUERY = "select * from gfc.LSI_ELGBLTY where INSURANCE_ID = ? and SYS_CD = ? and ACCT_TYPE in (?);
例如字符?
在上述字符串中出现3次。如何使用replace()
函数用三个不同的字符串替换此字符?
答案 0 :(得分:0)
如果使用final,则只能分配一次
final String QUERY = "select * from gfc.LSI_ELGBLTY where INSURANCE_ID = ? and
SYS_CD = ? and ACCT_TYPE in (?);
此功能可用于将字符串中的字符替换为其他字符并返回修改后的字符串
String replaceOneWithThreeOther(String str, String firstReplace,
String secondReplace, String thirdReplace) {
String result = str;
String replace = "\\?"
result.replaceFirst(replace, firstReplace);
result.replaceFirst(replace, secondReplace);
result.replaceFirst(replace, thirdReplace);
return result;
}
答案 1 :(得分:0)
如果您正在使用JDBC,则已经可以执行以下操作:
final String QUERY = "select * from gfc.LSI_ELGBLTY where INSURANCE_ID = ? and SYS_CD = ? and ACCT_TYPE in (?)";
Connection dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
PreparedStatement preparedStatement = null;
try {
preparedStatement = dbConnection.prepareStatement(QUERY);
preparedStatement.setString(1, firstValue); // setInt or what type you use
preparedStatement.setString(2, secondValue);
preparedStatement.setString(3, thirdValue);
ResultSet rs = preparedStatement.executeQuery(QUERY);
while (rs.next()) {
// do the read ...
}
} catch (SQLException e) {
e.printStackTrace();
}
或者,如果您想手动进行此替换,则可以按以下步骤进行:
List<String> values = Arrays.asList("1", "2", "3");
String QUERY = "select * from gfc.LSI_ELGBLTY where INSURANCE_ID = ? and SYS_CD = ? and ACCT_TYPE in (?)"; // here QUERY is not final
for (String value : values) {
QUERY = QUERY.replaceFirst("\\?", value);
}
System.out.println(QUERY);
输出为:
select * from gfc.LSI_ELGBLTY where INSURANCE_ID = 1 and SYS_CD = 2 and ACCT_TYPE in (3)
答案 2 :(得分:0)
如果合适,您绝对应该考虑使用PreparedStatement。
如果您需要自己执行更换,我不知道任何内置功能。但是,滚动自己的脚本非常简单。这里有几个版本:
static String replaceN(String s, String del, String... rep)
{
for(int i=0; i<rep.length; i++)
{
s = s.replaceFirst(del, rep[i]);
}
return s;
}
或更有效的版本:
static String replaceN2(String s, String del, String... rep)
{
String[] parts = s.split(del);
StringBuilder b = new StringBuilder(parts[0]);
for(int i=0; i<rep.length; i++)
{
b.append(rep[i]);
b.append(parts[i+1]);
}
return b.toString();
}
测试:
public static void main(String[] args)
{
String q = "select * from gfc.LSI_ELGBLTY where INSURANCE_ID = ? and SYS_CD = ? and ACCT_TYPE in (?);";
System.out.println(replaceN(q, "\\?", "one", "two", "three"));
}
输出:
select * from gfc.LSI_ELGBLTY where INSURANCE_ID = one and SYS_CD = two and ACCT_TYPE in (three);
答案 3 :(得分:0)
由于您正在对QUERY
变量进行硬编码,因此建议您稍微调整QUERY
变量。
现在,我们的想法是用内部参数号将?
替换为{}
。
final String QUERY = "select * from gfc.LSI_ELGBLTY where INSURANCE_ID = {0} and SYS_CD = {1} and ACCT_TYPE in ({2})";
System.out.println(MessageFormat.format(QUERY,"1","2","3,4,5"));
这将产生如下输出
select * from gfc.LSI_ELGBLTY where INSURANCE_ID = 1 and SYS_CD = 2 and ACCT_TYPE in (3,4,5)