给出一个字符串,把两个以上的_替换成一个,如"Hello__world____are__you_ok?",处理后应为"Hello_world_are_you_ok?",示例代码如下:
利用正则表达式,一句话搞定版:
public static void main(String args[]){
String str="Hello__world____are__you_ok?";
System.out.println(str.replaceAll("[_]+","_"));
}
输出:
Hello_world_are_you_ok?
比较费事的版本:
public static String replace(String str){
int index;
while((index=str.indexOf("__")) != -1){
str=str.replace("__","_");
}
return str;
}
输出结果:
Hello_world_are_you_ok?