Java:将"HelloThere"转换为"hello_there"

Ali*_*ade 1 java

我想将文本中的所有大写字母转换为下划线,这里有一些例子

HelloThere -> "hello_there"
ItIsExample -> "it_is_example"
Run Code Online (Sandbox Code Playgroud)

我使用此代码但不起作用:

String regex = "([A-Z][a-z]+)";
String replacement = "$1_";
str.replaceAll(regex, replacement); 
return toLowerCase(str);
Run Code Online (Sandbox Code Playgroud)

Ste*_*n C 7

我使用此代码但不起作用

提示:Java字符串是不可变的.

这一行:

  str.replaceAll(regex, replacement); 
Run Code Online (Sandbox Code Playgroud)

不会改变str.它返回一个新的字符串......然后你扔在地板上.

改为:

 return str.replaceAll(regex, replacement).toLowerCase(); 
Run Code Online (Sandbox Code Playgroud)