用于检查 Java 中的字符串是否仅包含空格的程序

pythonserver side programmingprogramming更新于 2023/12/29 3:43:00

JAVA 中的空格表示空字符串或转义序列字符。在Java中,我们有一些内置函数,例如isEmpty(),len JAVA 表示空字符串或转义序列字符。在 Java 中,我们有一些内置函数,例如 isEmpty()、length()、isWhitespace() 和 charAt(),它们将用于检查 Java 中的字符串是否仅包含空格。程序中的空格仅用于格式化目的,例如 \n(换行符)、\t(水平制表符)、\v(垂直制表符)等。

语法

示例中使用了以下语法-

isEmpty()

内置函数 isEmpty() 定义给定的字符串是否为空。

length()

length() 是 Python 中的内置函数,它返回给定字符串的长度。

isWhitespace()

isWhitespace() 是 Python 中的内置函数,如果字符值传递给满足以下条件的参数,则返回 true空格。

charAt()

charAt() 是 Python 中的一个内置函数,它返回给定字符串的特定索引的字符。

算法

以下步骤如下-

步骤 1:我们将通过定义布尔数据类型的方法 check_whitespaces() 来启动程序,该方法接受 str 作为 String 类型的参数。

步骤 2:然后使用第一个 if 语句通过使用内置函数 isEmpty() 以及逻辑 OR 和 isEmpty() 等运算符来检查字符串是否为空。

步骤 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 个转义序列代表 valis 字符文字。


相关文章