在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
您可以首先使用String.trim(),然后对结果应用regex replace命令。
其他回答
可以使用字符串标记器
String str = " hello there ";
StringTokenizer stknzr = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(stknzr.hasMoreElements())
{
sb.append(stknzr.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
您可以首先使用String.trim(),然后对结果应用regex replace命令。
看到String.replaceAll。
使用正则表达式“\s”并替换为“”。
然后使用String.trim。
你应该这样做
String mytext = " hello there ";
mytext = mytext.replaceAll("( +)", " ");
把+放在圆括号内。
String myText = " Hello World ";
myText = myText.trim().replace(/ +(?= )/g,'');
// Output: "Hello World"