Java判断字符串的前9位是否相等
时间: 2023-06-25 15:03:58 浏览: 84
可以使用 Java 中的 substring()
方法获取字符串的前9位,然后再进行比较。下面是一个示例代码:
String str = "1234567890";
if (str.length() >= 9 && str.substring(0, 9).equals("123456789")) {
System.out.println("前9位相等");
} else {
System.out.println("前9位不相等");
}
在代码中,首先判断字符串的长度是否大于等于9,然后使用 substring()
方法获取前9位,最后进行比较。如果相等,则输出“前9位相等”,否则输出“前9位不相等”。
相关问题
java字符串判断相等_java判断字符串是否相等的方法
Java中判断字符串是否相等有以下几种方法:
- 使用equals()方法判断字符串是否相等
String s1 = "hello";
String s2 = "world";
if (s1.equals(s2)) {
System.out.println("s1 is equal to s2");
} else {
System.out.println("s1 is not equal to s2");
}
- 使用equalsIgnoreCase()方法判断字符串是否相等,不区分大小写
String s1 = "Hello";
String s2 = "hello";
if (s1.equalsIgnoreCase(s2)) {
System.out.println("s1 is equal to s2");
} else {
System.out.println("s1 is not equal to s2");
}
- 使用compareTo()方法判断字符串是否相等,返回值为0表示相等
String s1 = "hello";
String s2 = "hello";
if (s1.compareTo(s2) == 0) {
System.out.println("s1 is equal to s2");
} else {
System.out.println("s1 is not equal to s2");
}
注意:以上方法中,使用“==”判断两个字符串是否相等是不正确的,应该使用equals()方法来判断。
Java判断字符串是否相等
在Java中,判断两个字符串是否相等可以使用equals方法。该方法返回一个boolean类型的值,如果两个字符串相等则返回true,否则返回false。需要注意的是,不能使用==运算符来判断两个字符串是否相等,因为这个运算符只能够确定两个字符串是否存放在同一个位置上。而equals方法则是比较两个字符串的内容是否相等。下面是一个例子:
String str1 = "hello"; String str2 = "world"; if(str1.equals(str2)){ System.out.println("两个字符串相等"); }else{ System.out.println("两个字符串不相等"); }
输出结果为“两个字符串不相等”。
相关推荐













