day08--String类的判断方法&获取方法

This commit is contained in:
2025-12-30 11:51:20 +08:00
parent f78ab1d6ba
commit 1e1375841b
2 changed files with 97 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
package com.inmind.string01;
/*
常用类_String的比较的方法_equals_equalsIgnoreCase
String的比较
==表示比较String对象的地址其实没有任何意义==一般用于基本数据类型的值是否相等比较
equals表示比较String对象地址所指向的内容
比较的方法:
public boolean equals (Object anObject) :将此字符串与指定对象进行比较。
public boolean equalsIgnoreCase (String anotherString) :将此字符串与指定对象进行比较,忽略大小
写。
*/
public class Demo03 {
public static void main(String[] args) {
String s1 = "abcd";
//通过构造方法创建s2
String s2 = new String(s1);
System.out.println(s1== s2);//false
//往往引用数据类型比较的是内容,不能使用==号来比较,它比较的是地址
boolean result = s1.equals(s2);
System.out.println(result);//true,比较的是地址指向的内容!!!!
System.out.println("----------------");
String s3 = "AbCd";
System.out.println(s1 == s3);//false
System.out.println(s1.equals(s3));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}

View File

@@ -0,0 +1,67 @@
package com.inmind.string01;
/*
常用类_String的获取方法_length_concat_charAt_indexOf_subString
public int length () :返回此字符串的长度。
public String concat (String str) :将指定的字符串连接到该字符串的末尾。
public char charAt (int index) :返回指定索引处的 char值。
public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
public int indexOf(String str, int fromIndex)
public String substring (int beginIndex) 返回一个子字符串从beginIndex开始截取字符串到字符
串结尾。
public String substring (int beginIndex, int endIndex) 返回一个子字符串从beginIndex到endIndex截取字符串。含beginIndex不含endIndex。
*/
public class Demo04 {
public static void main(String[] args) {
//public String substring (int beginIndex) 返回一个子字符串从beginIndex开始截取字符串到字符串结尾。
//public String substring (int beginIndex, int endIndex) 返回一个子字符串从beginIndex到endIndex截取字符串。含beginIndex不含endIndex。
String str = "123javahelloworld321";
//截取第一个helloworld,到字符串末尾的一个子字符串
String substring = str.substring(7);
System.out.println(substring);
//只截取helloworld作为子字符串
System.out.println(str.substring(7, 17));//java中包头不包尾
}
private static void method04() {
//public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
//public int indexOf(String str, int fromIndex)
String str = "123java321java54321";
//查询第一个j的位置
int index = str.indexOf("j");
System.out.println(index);//3
//查询第一个321的索引
index = str.indexOf("321");
// index = str.indexOf("abc"); 如果没有找到子字符串,返回-1
System.out.println(index);//7
//查询第二个321的索引
index = str.indexOf("321", 8);
System.out.println(index);//16
}
private static void method03() {
//public char charAt (int index) :返回指定索引处的 char值。
String str = "helloworld";
//获取w这个字符
char c = str.charAt(5);
System.out.println(c);
}
private static void method02() {
//public String concat (String str) :将指定的字符串连接到该字符串的末尾。
String s1 = "hello";
String newStr = s1.concat("world");
System.out.println(newStr);//helloworld
}
private static void method01() {
//public int length () :返回此字符串的长度。
String s = "123456";
System.out.println(s.length());//6
System.out.println("abc".length());//3
}
}