正则表达式“ \\ s”与字符串中的空格匹配。该replaceAll()
方法接受字符串,并且正则表达式用给定的字符串替换匹配的字符。要从输入字符串中删除所有空白,请绕过上面提到的正则表达式和一个空字符串作为输入,在其上调用replaceAll()方法。
public class RemovingWhiteSpaces { public static void main( String args[] ) { String input = "Hi welcome to nhooo"; String regex = "\\s"; String result = input.replaceAll(regex, ""); System.out.println("Result: "+result); } }
输出结果
Result: Hiwelcometonhooo
类似地,appendReplacement()方法接受一个字符串缓冲区和一个替换字符串,并使用给定的替换字符串附加匹配的字符,并将其附加到字符串缓冲区。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemovingWhiteSpaces { public static void main( String args[] ) { Scanner sc = new Scanner(System.in); System.out.println("Enter input string: "); String input = sc.nextLine(); String regex = "\\s"; String constants = ""; System.out.println("Input string: \n"+input); //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //匹配字符串中的已编译模式 Matcher matcher = pattern.matcher(input); //创建一个空的字符串缓冲区 StringBuffer sb = new StringBuffer(); while (matcher.find()) { constants = constants+matcher.group(); matcher.appendReplacement(sb, ""); } matcher.appendTail(sb); System.out.println("Result: \n"+ sb.toString()+constants ); } }
输出结果
Enter input string: this is a sample text with white spaces Input string: this is a sample text with white spaces Result: thisisasampletextwithwhitespaces
public class Just { public static void main(String args[]) { String input = "This is a sample text with spaces"; String str[] = input.split(" "); String result = ""; for(int i=0; i<str.length; i++) { result = result+str[i]; } System.out.println("Result: "+result); } }
输出结果
Result: Thisisasampletextwithspaces