gpt4 book ai didi

java - 构建字符串避免重复的最佳方法

转载 作者:行者123 更新时间:2023-11-30 10:29:11 24 4
gpt4 key购买 nike

我有一个将在 URL 中使用的硬编码字符串,我想知道构建这个字符串的最佳方法是什么,而不必重复单词 country, or, and, number?这是一个缩短的版本,因为 URL 中将包含更多国家和数字。

String url = "&filter=country='UK' or "
+ "country='FR' or "
+ "country='CA' or "
+ "country='US' and "
+ "number='123' and "
+ "number='789'";

最佳答案

您可以结合使用 StringBuilderString 格式来构建特定的 URL 参数化。

这是一个例子:

// test data
List<String> countries = Arrays.asList("UK", "FR","CA", "US");
List<String> numbers = Arrays.asList("123", "789");

// these can be compile-time constants
String disjunct = " or ";
String conjunct = " and ";
String countryFormat = "country='%s'";
String numberFormat = "number='%s'";

// result
StringBuilder result = new StringBuilder("&filter=");

// adding countries
for (String country: countries) {
result.append(String.format(countryFormat, country)).append(disjunct);
}
// removing last "or"
result.delete(result.lastIndexOf(disjunct), result.length());

// adding first "and"
result.append(conjunct);

// adding numbers
for (String number: numbers) {
result.append(String.format(numberFormat, number)).append(conjunct);
}
// removing last "and"
result.delete(result.lastIndexOf(conjunct), result.length());

// printing result
System.out.println(result);

输出

&filter=country='UK' or country='FR' or country='CA' or country='US' and number='123' and number='789'

关于java - 构建字符串避免重复的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44158659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com