Java 程序检查字符串结尾
通常,endswith() 方法 在 Java 中用于检查给定字符串是否以特定后缀字符串结尾。如果子字符串以特定字符串结尾,则它将返回布尔值 true,否则如果未找到该值,则返回 false。
语法public boolean endsWith(String suffix)
问题陈述
编写一个程序,检查字符串是否以 Java 中的特定子字符串结尾 -
输入
str = demo
输出
The string ends with the word mo
检查字符串结尾的步骤
以下是检查特定子字符串的步骤 -
- 开始
- 创建一个字符串。
- 使用endsWith() 方法查看字符串是否以所需的子字符串结尾。
- 实现一个if-else 条件语句,根据结果打印相应的消息。
- 停止
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
Java 程序检查字符串结尾
以下是检查字符串结尾的 Java 程序 -
public class Demo { public static void main(String[] args) { String str = "demo"; if(str.endsWith("mo")) { System.out.println("The string ends with the word mo"); } else { System.out.println("The string does not end with the word mo"); } } }
输出
The string ends with the word mo
代码解释
假设以下为我们的字符串 -
String str = "demo";
现在,使用endsWith() 方法在 if-else 条件中检查子字符串“mo”。
if(str.endsWith("mo")) { System.out.println("The string ends with the word mo"); } else { System.out.println("The string does not end with the word mo"); }
在这篇文章中,我们学习了如何在 Java 中使用endsWith() 方法来检查字符串结尾。
广告