8.2 String方法:length、concat、charAt、indexOf、substring、toCharArray、getBytes、replace

想了解更多请查看java学习(idea版)

目录

字符串常用方法

length()、concat()、charAt()、indexOf()

字符串的截取方法substring()

toCharArray()、getBytes()、replace()

 


字符串常用方法

length()、concat()、charAt()、indexOf()

  • public int length():获取字符串当中含有的字符个数,拿到字符串长度。
  • public String concat(String str):将当前字符串和参数字符串拼接成为返回值新的字符串。
  • public char charAt(int index):获取指定索引位置的单个字符。(索引从0开始。)
  • public int indexOf(String str):查找参数字符串在本字符串当中首次出现的索引位置,如果没有返回-1值。

 

        String str1="adgbfADG!#%1234WR";
        String str2="ccccc";

        //1 获取字符串穿度
        int len=str1.length();
        System.out.println(len);
        //2 字符串拼接
        String con=str1.concat(str2);
        System.out.println(con);
        //3 获取指定索引位置的单个字符
        char ch= str1.charAt(1);
        System.out.println(ch);
        //3 查找参数字符串在本字符串当中首次出现的索引位置,如果没有返回-1值。
        int index=str1.indexOf(123);
        System.out.println(index);

    // 查找参数字符串在本来字符串当中出现的第一次索引位置 ,索引从0开始
    // 如果根本没有,返回-1值
    String original = "HelloWorldHelloWorld";
    int index = original.indexOf("llo");
    System.out.println("第一次索引值是:" + index); // 2
    System.out.println("HelloWorld".indexOf("abc")); // -1

字符串的截取方法substring()

public String substring(int index):截取从参数位置一直到字符串末尾,返回新字符串。
public String substring(int begin, int end):截取从begin开始,一直到end结束,中间的字符串。
备注:[begin,end),包含左边,不包含右边。


        String str1 = "HelloWorld";
        String str2 = str1.substring(5);
        System.out.println(str2); // World,新字符串

        String str3 = str1.substring(4, 7);
        System.out.println(str3); // oWo

toCharArray()、getBytes()、replace()

public char[] toCharArray():将当前字符串拆分成为字符数组作为返回值。
public byte[] getBytes():获得当前字符串底层的字节数组。
public String replace(CharSequence oldString, CharSequence newString):
将所有出现的老字符串替换成为新的字符串,返回替换之后的结果新字符串。
备注:CharSequence意思就是说可以接受字符串类型。

    public static void main(String[] args) {
        String str1="hello world java welcome";
        //1字符串拆分成字符数组
        char[] chars= str1.toCharArray();
        System.out.println("字符数值地址"+chars);
        for (int i = 0; i < chars.length; i++) {
            System.out.print(chars[i]+"-");
        }
        System.out.println("\n----------------\n");

        //2 字符串拆分为字节数组
        byte[] bytes=str1.getBytes();
        System.out.println("字节数组地址:"+bytes);
        for (int i = 0; i < bytes.length; i++) {
            System.out.print(bytes[i]+"-");
        }
        System.out.println("\n----------------\n");

        //3 字符串替换
        String str2=str1.replace("j","J");
        System.out.println("替换后的字符串"+str2);
    }

结果:

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值