Java如何判断字符串结尾是否为所求字符串
时间: 2023-09-08 19:14:45 浏览: 51
Java中可以使用String类的endsWith()方法来判断一个字符串是否以指定的字符串结尾。该方法返回一个boolean值,如果字符串以指定的字符串结尾,则返回true,否则返回false。
以下是endsWith()方法的语法:
```
public boolean endsWith(String suffix)
```
其中,suffix为指定的字符串,该方法会判断当前字符串是否以suffix结尾。
示例代码:
```java
String str = "Hello, world!";
boolean endsWithExclamation = str.endsWith("!"); // false
boolean endsWithWorld = str.endsWith("world!"); // true
```
在上面的示例中,endsWithExclamation变量记录了str是否以感叹号结尾,endsWithWorld变量记录了str是否以"world!"结尾。
相关问题
Java 判断字符串是否以另一个字符串结尾
可以使用 endsWith() 方法来判断一个字符串是否以另一个字符串结尾。例如:
String str1 = "hello world";
String str2 = "world";
if (str1.endsWith(str2)) {
System.out.println("str1 ends with str2");
} else {
System.out.println("str1 does not end with str2");
}
输出结果为:"str1 ends with str2"。
java判断字符串是以下划线数字结尾的
在Java中,可以使用正则表达式来判断字符串是否以下划线和数字结尾。下面是一个示例代码:
```java
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str1 = "abc_123";
String str2 = "def_456";
String str3 = "ghi_789a";
// 使用正则表达式判断字符串是否以下划线和数字结尾
boolean isEndWithUnderscoreAndNumber1 = Pattern.matches(".*_[0-9]+$", str1);
boolean isEndWithUnderscoreAndNumber2 = Pattern.matches(".*_[0-9]+$", str2);
boolean isEndWithUnderscoreAndNumber3 = Pattern.matches(".*_[0-9]+$", str3);
System.out.println("str1 ends with underscore and number: " + isEndWithUnderscoreAndNumber1); // 输出:true
System.out.println("str2 ends with underscore and number: " + isEndWithUnderscoreAndNumber2); // 输出:true
System.out.println("str3 ends with underscore and number: " + isEndWithUnderscoreAndNumber3); // 输出:false
}
}
```
上述代码使用`Pattern.matches()`方法和正则表达式`.*_[0-9]+$`来判断字符串是否以下划线和数字结尾。如果返回`true`,则表示字符串满足条件;如果返回`false`,则表示字符串不满足条件。