繁体   English   中英

如何从列表值中执行字符串操作,如下所示

[英]How can i do String manipulation from list values like below

我想动态地用字符串值替换字符串而不用硬编码。 比如'list.get(0)'

在第一次迭代中==> str = str.replace("{Name}", 'One');

在第二次迭代中==> str = str.replace("{subInterfaceId}", 'Two');

提前致谢。

String str = "Iamstillquite/{Name}/newtoJava/programm/ingandIam/{subInterfaceId}/tryingtoupdate/anexisting";
List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");    

for (String s : list) {
    str = str.replace("{Name}", s);
}   

预期产出:

String finalstr = "Iamstillquite/One/newtoJava/programm/ingandIam/Two/tryingtoupdate/anexisting";

你需要一张Map 它将键( {Name} )映射到值( One )。

Map<String, String> map = new HashMap<>();
map.put("{Name}", "One");
map.put("{subInterfaceId}", "Two");

for (String key : map.keySet()) {
    str = str.replace(key, map.get(key));
}

最好的方法是使用正则表达式:

List<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
String str = "Iamstillquite/{Name}/newtoJava/programm/ingandIam/{subInterfaceId}/tryingtoupdate/anexisting";
String regex = "(?<=^[^\\{]+)\\{.*?\\}";
for (String s : list)
{
    str = str.replaceAll(regex, s);
}
System.out.println(str);

输出:

Iamstillquite/One/newtoJava/programm/ingandIam/Two/tryingtoupdate/anexisting

好处:您不必更改任何现有数据,正则表达式对于搜索和替换内容非常有用。

此外,您可以保持输入String str不变,这与此处给出的其他答案不同。

    List<String> list = new ArrayList<>();
    list.add("One");
    list.add("Two");
    int counter = 0;
    String str = new String("Iamstillquite/{Name0}/newtoJava/programm/ingandIam/{Name1}/tryingtoupdate/anexisting");
    for (String s : list) {
        str = str.replace("{Name" + counter + "}", s);
        counter++;
    }

您可能会发现使用计数器可以更轻松地进行更换。 这就是为什么你需要将要替换的字符串命名为{Name0},{Name1},{Name2} ......虽然它没有任何困难,因为如果需要你可以在循环中完成它。

您可以使用正则表达式和匹配器使用以下解决方案替换{}内的任何内容:

        Pattern pat1 = Pattern.compile("(\\{[\\w]+\\})");
        int index = 0;
        Matcher m1 = pat1.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(m1.find() && index<list.size()){ //checking index is necessary to not throw `ArrayIndexOutofBoundsException`
            m1.appendReplacement(sb, list.get(index));
            index += 1;
        }
        m1.appendTail(sb);
        System.out.println(sb);

输出:

Iamstillquite/One/newtoJava/programm/ingandIam/Two/tryingtoupdate/anexisting

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM