java如何去掉下划线
去除字符串中的下划线
在Java中去除字符串中的下划线可以使用多种方法,以下是几种常见的实现方式:
使用String的replace方法
String original = "hello_world";
String result = original.replace("_", "");
System.out.println(result); // 输出 "helloworld"
使用正则表达式替换
String original = "hello_world_123";
String result = original.replaceAll("_", "");
System.out.println(result); // 输出 "helloworld123"
使用StringBuilder处理
String original = "hello_world";
StringBuilder builder = new StringBuilder();
for (char c : original.toCharArray()) {
if (c != '_') {
builder.append(c);
}
}
String result = builder.toString();
System.out.println(result); // 输出 "helloworld"
使用Java 8的Stream API
String original = "hello_world";
String result = original.chars()
.filter(c -> c != '_')
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(result); // 输出 "helloworld"
性能考虑
对于简单的替换操作,String.replace()方法通常是最直接和高效的选择。如果需要处理大量数据或复杂模式,正则表达式可能更合适,但性能会稍低。
扩展应用
如果需要去除其他特定字符,只需将上述代码中的下划线替换为目标字符即可。例如去除所有数字:

String original = "hello123_world";
String result = original.replaceAll("[0-9]", "");
System.out.println(result); // 输出 "hello_world"





