Java面向对象-- String 类 常用方法及基本使用

首先来学习基本使用Jdk api chm文档:

点击 左上角-显示:

 

1, char chartAt(int index) 返回指定索引处的char值

这里的index 是从0开始的;

package com.xuyigang1234.chp02.string;

public class Demo01 {
    public static void main(String[] args) {
        String name="小白";
        char name1=name.charAt(1);
        System.out.println("name1为:"+name1);
        String aa="我爱学习";
        for(int i=0;i<aa.length();i++) {
            System.out.println(aa.charAt(i)+" ");
        }
        
    }

}

2,int length() 返回字符串的长度;

3,int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。

package com.java1234.chap03.sec08;
 
public class Demo06 {
 
    public static void main(String[] args) {
        // indexOf方法使用实例
        String str="abcdefghijdklmoqprstuds";
        System.out.println("d在字符串str中第一次出现的索引位置:"+str.indexOf('d'));
        System.out.println("d在字符串str中第一次出现的索引位置,从索引4位置开始:"+str.indexOf('d',4));
    }
}

4,String substring(int beginIndex)   返回一个新的字符串,它是此字符串的一个子字符串。

package com.java1234.chap03.sec08;
 
public class Demo07 {
 
    public static void main(String[] args) {
        // substring方式读取
        String str="不开心每一天";
        String str2="不开心每一天,不可能";
        String newStr=str.substring(1);
        System.out.println(newStr);
        String newStr2=str2.substring(1, 6);
        System.out.println(newStr2);
    }
}

5,public String toUpperCase()  String 中的所有字符都转换为大写

package com.java1234.chap03.sec08;
 
public class Demo08 {
 
    public static void main(String[] args) {
        String str="I'm a boy!";
        String upStr=str.toUpperCase(); // 转成大写
        System.out.println(upStr);
        String lowerStr=upStr.toLowerCase(); // 转成小写
        System.out.println(lowerStr);
    }
}

猜你喜欢

转载自www.cnblogs.com/xyg-zyx/p/9824442.html