在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
在Java中寻找快速、简单的方法来更改此字符串
" hello there "
变成了这样的东西
"hello there"
在这里我用一个空格替换了所有这些多个空格,除了我还希望字符串开头的一个或多个空格消失。
像这样的事情能让我在一定程度上做到
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
但事实并非如此。
当前回答
这是删除字符串中任何空白的最简单方法。
public String removeWhiteSpaces(String returnString){
returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
return returnString;
}
其他回答
trim()方法删除开头和结尾的空格,使用regex“\s+”的replaceAll("regex", "string to replace")方法匹配多个空格,并将其替换为单个空格
myText = myText.trim().replaceAll("\\s+"," ");
试试这个:
String after = before.trim().replaceAll(" +", " ");
另请参阅
String.trim () 返回字符串的副本,省略前导和尾随空格。 regular-expressions.info /重复
没有trim()正则表达式
只用一个replaceAll也可以做到这一点,但这比trim()解决方案可读性差得多。尽管如此,这里提供它只是为了展示regex可以做什么:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
有三名候补:
^_+:字符串开头的任意空格序列 匹配并替换为$1,它捕获空字符串 _+$:字符串结尾的任意空格序列 匹配并替换为$1,它捕获空字符串 (_)+:不匹配上述任何一个空格序列,表示它在中间 匹配并替换为$1,它捕获单个空格
另请参阅
regular-expressions.info /锚
试试这个。
示例代码
String str = " hello there ";
System.out.println(str.replaceAll("( +)"," ").trim());
输出
hello there
首先,它将所有空格替换为单个空格。我们必须要做修剪字符串,因为开始的字符串和结束的字符串,它会取代所有的空格,如果字符串有空格在开始的字符串和结束的字符串,所以我们需要修剪它们。然后你会得到你想要的字符串。
String str = " hello world"
首先减少空间
str = str.trim().replaceAll(" +", " ");
第一个字母大写,其他字母小写
str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
这对我很有效
scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();
其中filter跟在function后面,scan是输入字符串:
public String filter(String scan, String regex, String replace) {
StringBuffer sb = new StringBuffer();
Pattern pt = Pattern.compile(regex);
Matcher m = pt.matcher(scan);
while (m.find()) {
m.appendReplacement(sb, replace);
}
m.appendTail(sb);
return sb.toString();
}