在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()方法。然后使用你的mytext。replaceAll("()+", " ")。
其他回答
这对我来说非常有效:sValue = sValue.trim()。replaceAll("\\s+", " ");
检查下这个吗……
public static void main(String[] args) {
String s = "A B C D E F G\tH I\rJ\nK\tL";
System.out.println("Current : "+s);
System.out.println("Single Space : "+singleSpace(s));
System.out.println("Space count : "+spaceCount(s));
System.out.format("Replace all = %s", s.replaceAll("\\s+", ""));
// Example where it uses the most.
String s = "My name is yashwanth . M";
String s2 = "My nameis yashwanth.M";
System.out.println("Normal : "+s.equals(s2));
System.out.println("Replace : "+s.replaceAll("\\s+", "").equals(s2.replaceAll("\\s+", "")));
}
如果字符串只包含单个空格,则replace()将不替换,
如果空格多于一个,则执行replace()操作并删除空格。
public static String singleSpace(String str){
return str.replaceAll(" +| +|\t|\r|\n","");
}
计算字符串中的空格数。
public static String spaceCount(String str){
int i = 0;
while(str.indexOf(" ") > -1){
//str = str.replaceFirst(" ", ""+(i++));
str = str.replaceFirst(Pattern.quote(" "), ""+(i++));
}
return str;
}
pattern .quote("?")返回字面模式字符串。
trim()方法删除开头和结尾的空格,使用regex“\s+”的replaceAll("regex", "string to replace")方法匹配多个空格,并将其替换为单个空格
myText = myText.trim().replaceAll("\\s+"," ");
管柱。替换(“s+”,“”);
下面的代码将压缩单词之间的空白,并删除字符串开头和结尾的空白
String input = "\n\n\n a string with many spaces, \n"+
" a \t tab and a newline\n\n";
String output = input.trim().replaceAll("\\s+", " ");
System.out.println(output);
这将输出一个包含许多空格、制表符和换行符的字符串
注意,任何不可打印的字符,包括空格、制表符和换行符将被压缩或删除
欲了解更多信息,请参阅相应的文档:
字符串#修剪()方法 String#replaceAll(字符串正则表达式,字符串替换)方法 有关Java正则表达式实现的信息,请参阅Pattern类的文档