Java 检查字符串是否只包含空白字符
Java中的空白字符表示为空字符串或转义序列字符。在Java中,我们有一些内置函数,如isEmpty()、length()、isWhitespace()和charAt(),用于检查字符串是否只包含空白字符。程序中的空白字符仅用于格式化字符串,例如\n
(换行符)、\t
(水平制表符)、\v
(垂直制表符)等。
语法
示例中使用以下语法-
isEmpty()
内置函数isEmpty()定义给定的字符串是否为空。
length()
length()是Python中的内建函数,它返回给定字符串的长度。
isWhitespace()
isWhitespace()是Python中的一个内置函数,如果将字符值传递给参数并满足空格要求,则返回true。
charAt()
charAt() 是Python中的内置函数,它返回给定字符串特定索引处的字符。
步骤
以下是具体步骤:
步骤1:我们将通过定义一个布尔型的方法check_whitespaces()来开始程序,该方法接受一个类型为String的str作为参数。
步骤2:然后使用第一个if语句通过使用内置函数isEmpty()以及逻辑或和isEmpty()操作符来检查字符串是否为null或空字符串。
步骤3:接下来,它将使用for循环,其中变量i遍历所有给定字符串(如str1、str2、str3、str4和str5)的长度。然后使用内置函数charAt()来接受变量i以将字符串的每个字符分隔并将其存储在变量c中。
步骤4:然后使用第二个if语句来设置条件,检查字符是否满足空格要求,使用内置函数isWhitespaces(),如果条件不满足,则返回false,否则返回true。
步骤5:现在,它将使用主函数,并开始初始化不同的字符串来设置一些值,例如转义字符(\t和\n)、文本字符串(“Hello”)和空格(“ ”)来检查空格。
步骤6:最后,它将通过调用名为check_whitespaces()的方法来打印结果。
示例
在下面的示例中,我们将将转义序列字符、空格和字符串文本存储到相应的变量中,并检查空格的存在。
public class whitespace_in_java {
public static boolean check_whitespace(String str) {
// Check whether the string is null or empty
if (str == null || str.isEmpty()) {
return false;
}
// The for loop iterate through each character of the string
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// Check whether the character does not satisfy for whitespace
if (!Character.isWhitespace(c)) {
return false;
}
}
// Return true if the character satisfies for whitespace
return true;
}
public static void main(String[] args) {
// Initializing different strings
String str_1 = " \t ";
String str_2 = " Hello ";
String str_3 = " ";
String str_4 = "World";
String str_5 = " \n ";
// Printing of all the given string
System.out.println("The following string results are:-");
System.out.println(check_whitespace(str_1));
System.out.println(check_whitespace(str_2));
System.out.println(check_whitespace(str_3));
System.out.println(check_whitespace(str_4));
System.out.println(check_whitespace(str_5));
}
}
输出
The following string results are:-
true
false
true
false
true
结论
空格通常在每种编程语言中用于设置代码的格式。空格可以提高代码的可读性,使每个用户更好地理解程序。在Java中,一共有8个转义序列,用于表示有效的字符字面量。