java如何判断空格
判断字符串中的空格
在Java中,可以使用多种方法判断字符串中是否包含空格或空白字符。
使用String类的contains方法
String str = "Hello World";
boolean hasSpace = str.contains(" ");
System.out.println(hasSpace); // 输出true
使用Character类的isWhitespace方法
String str = "Hello\tWorld";
boolean hasWhitespace = false;
for (char c : str.toCharArray()) {
if (Character.isWhitespace(c)) {
hasWhitespace = true;
break;
}
}
System.out.println(hasWhitespace); // 输出true
使用正则表达式

String str = "Hello\nWorld";
boolean hasWhitespace = str.matches(".*\\s.*");
System.out.println(hasWhitespace); // 输出true
判断字符串是否全为空格
使用String类的trim方法
String str = " ";
boolean isAllSpace = str.trim().isEmpty();
System.out.println(isAllSpace); // 输出false,因为trim后为空
使用正则表达式
String str = " \t\n";
boolean isAllWhitespace = str.matches("\\s+");
System.out.println(isAllWhitespace); // 输出true
检查字符串开头或结尾的空格
使用String类的startsWith或endsWith方法

String str = " Hello";
boolean startsWithSpace = str.startsWith(" ");
System.out.println(startsWithSpace); // 输出true
使用正则表达式
String str = "World ";
boolean endsWithSpace = str.matches(".*\\s$");
System.out.println(endsWithSpace); // 输出true
获取空格数量
遍历字符串统计空格
String str = "H e l l o";
int spaceCount = 0;
for (char c : str.toCharArray()) {
if (c == ' ') {
spaceCount++;
}
}
System.out.println(spaceCount); // 输出4
使用Java 8流式处理
long spaceCount = "H e l l o".chars().filter(c -> c == ' ').count();
System.out.println(spaceCount); // 输出4






