栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

刷题常用的String方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

刷题常用的String方法

(1)public String toString() 返回字符串本身

代码实例:

System.out.println("hello world".toString());  //输出:hello world
(2)public char charAt(int index) 查找字符串下标为inde的字符,并且返回

代码实例:

System.out.println("hello world".charAt(0));  //输出:h
System.out.println("hello world".charAt(6));  //输出:w
System.out.println("hello world".charAt(5));  //输出:“ ”
(3)public String substring(int beginIndex, int endIndex) 在当前字符串中,从beginIndex开始截取,截取到endIndex的新字符串,返回新字符串。 注意:beginIndex是包括的,endIndex是不包括的。
左闭右开:[beginIndex, endIndex) 或 [beginIndex, endIndex-1]。

代码实例:

String str1 = "ABCDEFGH".substring(2, 6);
System.out.println(str1);  //输出:CDEF
(4)   public String toLowerCase() 
        将字符串全都转换成小写字母。         public String toUpperCase()        将字符串全都转换成大写字母
       代码实例:
System.out.println("Student".toLowerCase());  //输出:student
System.out.println("studenT".toUpperCase());  //输出:STUDENT
(5)public String trim() 去除字符串前后的空格。

代码实例:

System.out.println("    hello   world  ".trim());  //输出:hello   world
(6)public char[] toCharArray() 将字符串转换成char[]数组,并返回。 代码实例:
char[] chars = "student".toCharArray();
for (char c : chars) {
    System.out.print(c + "  ");
}
//'s' 't' 'u' 'd' 'e' 'n' 't'
(7)public int indexOf(String str)
返回某个子字符串在当前字符串中第一次出现的下标,没有就返回-1。 public int lastIndexOf(String str)
返回某个子字符串在当前字符串中最后一次出现的下标,没有就返回-1。

代码实例:

System.out.println("aaabbssddcdd".indexOf("dd"));  //输出:7
System.out.println("aaabbssddcdd".lastIndexOf("dd"));  //输出:10
(8)public boolean equals(Object anObject)
         判断当前字符串内容是否与后面字符串内容相同。          注意:比较两个字符串内容是否相等不能使用“==”。

代码实例:

System.out.println("student".equals("student"));  //输出:true
System.out.println("student".equals("STUDENT"));  //输出:false
(9) public boolean equalsIgnoreCase(String anotherString)
忽略大小写,判断当前字符串内容是否与后面字符串内容相同。

代码实例:

System.out.println("student".equalsIgnoreCase("STUDENT"));  //输出:true
(10) public boolean contains(CharSequence s)
判断前面的字符串是否包含后面的字字符串。

代码实例:

System.out.println("hello World".contains("hello"));  //输出:true
System.out.println("hello World".contains("hello!"));  //输出:false
System.out.println("good".contains("job"));  //输出:false
(11)public String concat(String s) 将一个字符串拼接到另一个字符串的后面

代码实例:
 

        String str="Hello";
        String str1="world!";
        System.out.println(str.concat(str1));//Hello world!
(12) public String[] split(String regex)
将当前字符串以regex字符串隔开,隔开后的片段以String[]形式返回。

代码实例:

​
String[] str = "I-am-a-student".split("-");
for (String x: str) {
    System.out.print(x );  //输出:I am a student
}

​

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/731388.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号