字符串的比较相关方法和获取相关方法
判断功能的方法
~public boolean equals (Object anObject) :将此字符串与指定对象进行比较
~public boolean equalsIgnoreCase (String anotherString) :将此字符串与指定对象进行比较,忽略大小写
方法演示,代码如下:
public class String_Demo01 { public static void main(String[] args) { // 创建字符串对象 String s1 = "hello"; String s2 = "hello"; String s3 = "HELLO"; // boolean equals(Object obj):比较字符串的内容是否相同 System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // false System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); //boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写 System.out.println(s1.equalsIgnoreCase(s2)); // true System.out.println(s1.equalsIgnoreCase(s3)); // true System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); } }
Object 是” 对象”的意思,也是一种引用类型。作为参数类型,表示任意对象都可以传递到方法中
获取功能的方法
~public int length () :返回此字符串的长度。
~public String concat (String str) :将指定的字符串连接到该字符串的末尾。
~public char charAt (int index) :返回指定索引处的 char值。
~public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
~public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
~public String substring (int beginIndex, int endIndex) :返回一个子字符串,从beginIndex到
endIndex截取字符串。含beginIndex,不含endIndex。
方法演示,代码如下:
public class String_Demo02 { public static void main(String[] args) { //创建字符串对象 String s = "helloworld"; // int length():获取字符串的长度,其实也就是字符个数 System.out.println(s.length()); System.out.println("‐‐‐‐‐‐‐‐"); // String concat (String str):将将指定的字符串连接到该字符串的末尾. String s = "helloworld"; String s2 = s.concat("**hello itheima"); System.out.println(s2);// helloworld**hello itheima // char charAt(int index):获取指定索引处的字符 System.out.println(s.charAt(0)); System.out.println(s.charAt(1)); System.out.println("‐‐‐‐‐‐‐‐"); // int indexOf(String str):获取str在字符串对象中第一次出现的索引,没有返回‐1 System.out.println(s.indexOf("l")); System.out.println(s.indexOf("owo")); System.out.println(s.indexOf("ak")); System.out.println("‐‐‐‐‐‐‐‐"); // String substring(int start):从start开始截取字符串到字符串结尾 System.out.println(s.substring(0)); System.out.println(s.substring(5)); System.out.println("‐‐‐‐‐‐‐‐"); // String substring(int start,int end):从start到end截取字符串。含start,不含end。 System.out.println(s.substring(0, s.length())); System.out.println(s.substring(3,8)); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)