Java中String类的常用API整理

package justForFun;

//String类常用API
public class stringAPI {
    public static void main(String[] args) {
        // 1. public int length(): 获取字符串长度
        String name = "0123456789";
        System.out.println(name.length()); //10

        // 2. public char charAt(int index): 获取某个索引位置的字符
        char c = name.charAt(3);
        System.out.println(c); //3

        // 3. public char[] toCharArray(): 把字符串转换成字符数组
        char[] chars = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            System.out.print(chars[i] + " ");
            //0 1 2 3 4 5 6 7 8 9
        }
        System.out.println();

        /* 4. public String substring(int beginIndex, int endIndex)
              以字符串形式返回[beginIndex, endIndex)的内容
         */
        String name1 = "Do you still love me? yes/no";
        String subName1 = name1.substring(22, 25);
        System.out.println(subName1); //yes

        /* 5. public String substring(int beginIndex)
              以字符串形式返回[beginIndex, end)的内容
         */
        String name2 = "Do you love me";
        String subName2 = name2.substring(3);
        System.out.println(subName2); //you love me

        /* 6. public String replace(CharSequence target, CharSequence replacement)
              public String replace(char oldChar, char newChar)
              将target/oldChar换成replacement/newChar
         */
        String name3 = "Alright, I still love you.";
        String replaceName3 = name3.replace("still", "never");
        System.out.println(replaceName3);
        //Alright, I never love you.

        // 7. public boolean contains(CharSequence s): 判断s是否在字符串中
        System.out.println(name3.contains("love")); //true
        System.out.println(name3.contains("hate")); //false

        // 8. public boolean startsWith(String prefix): 判断字符串是否以prefix开头
        System.out.println(name3.startsWith("Alright")); //true

        // 9. public String[] split(String s): 按照某个内容把字符串分割成字符串数组返回
        String name4 = "arycra_07, arcray_07, aracry_07";
        String[] splitName4 = name4.split(", ");
        for (String s : splitName4) {
            System.out.print(s + " ");
            //arycra_07 arcray_07 aracry_07 
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AryCra_07

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值