如何使用java替换字符串中的特定单词?

时间:2014-10-11 11:38:08

标签: java string

我有这个字符串变量:

String a = "malam mingguan bareng geng motor kepominfo kemkominfo bem rema upi";

我想做的是取代" malam mingguan"到了" malam-mingguan"。输出将是这样的:

String a = "malam-mingguan bareng geng motor kepominfo kemkominfo bem rema upi";

我该怎么做?

3 个答案:

答案 0 :(得分:4)

使用String.replace

a = a.replace("malam mingguan", "malam-mingguan");

答案 1 :(得分:1)

您可以使用replaceAll函数。

代码:

String a = "malam mingguan bareng geng motor kepominfo kemkominfo bem rema upi";
System.out.println(a.replaceAll("(?<=malam)\\s(?=mingguan)", "-"));

输出:

malam-mingguan bareng geng motor kepominfo kemkominfo bem rema upi

答案 2 :(得分:0)

只需使用replaceAll

等正则表达式调用malam\s+mingguan即可
a.replaceAll("malam\\s+mingguan", "malam-mingguan");