Java 小白 是否以某字符串结尾

本文详细介绍了如何在Java中使用fun5()方法,通过实例探讨了String对象的endsWith()函数,帮助读者理解其在处理文件名或资源路径尾缀检查中的作用。
 private static void fun5() {
        String str="x、、xx.png";
        System.out.println(str.endsWith(".png"));
    }
public class homework {
    public static void main(String[] args) {
       fun5();
    }
 }
Java 中,判断字符串是否以数字结尾有以下几种常见方法: ### 方法一:使用正则表达式 正则表达式可以方便地匹配字符串的模式。使用 `\d+$` 可以匹配以一个或多个数字结尾字符串。示例代码如下: ```java import java.util.regex.*; public class Regex { public static void main(String[] args) { String sa = "abc123"; String sb = "abc123a"; Pattern pattern = Pattern.compile("\\d+$"); Matcher matcher = pattern.matcher(sa); if (matcher.find()) { System.out.println("字符串sa是以数字结尾的,结尾的数字是:" + matcher.group()); } else { System.out.println("字符串sa不是以数字结尾的"); } matcher.reset(sb); if (matcher.find()) { System.out.println("字符串sb是以数字结尾的,结尾的数字是:" + matcher.group()); } else { System.out.println("字符串sb不是以数字结尾的"); } } } ``` 该代码通过 `Pattern` 类和 `Matcher` 类来使用正则表达式,`Pattern.compile("\\d+$")` 编译了一个正则表达式,然后使用 `Matcher` 类的 `find()` 方法来查找匹配的内容。如果找到匹配,则说明字符串以数字结尾,并可以通过 `matcher.group()` 获取结尾的数字 [^1]。 ### 方法二:通过字符判断 可以通过检查字符串的最后一个字符是否为数字来判断字符串是否以数字结尾。示例代码如下: ```java public class Main { public static Boolean isStartWithNumber(String str) { Boolean flag = null; try { flag = true; java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("[0-9]*"); java.util.regex.Matcher isNum = pattern.matcher(str.charAt(str.length() - 1) + ""); if (!isNum.matches()) { return false; } } catch (Exception e) { e.printStackTrace(); return false; } return flag; } public static void main(String[] args) { String str1 = "abc123"; String str2 = "abc123a"; System.out.println(isStartWithNumber(str1)); System.out.println(isStartWithNumber(str2)); } } ``` 该代码定义了 `isStartWithNumber` 方法,通过 `Pattern` 和 `Matcher` 类判断字符串的最后一个字符是否为数字。如果最后一个字符不是数字,则返回 `false` [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值