java Sting类函数

一、判断字符串中是否包含某个字符串(字符): contains()

public class
test {
    public static void main(String[] args) {
        String x="hello world";
        boolean status=x.contains("hello");
        System.out.println(status);
    }
}

输出结果:
true

二、获取字符串长度: length()

public class
test {
    public static void main(String[] args) {
        String x="hello world";
        int l=x.length();
        System.out.println(l);
    }
}

三、截取字符串: substring()

public class
test {
    public static void main(String[] args) {
        String x="hello world";
        System.out.println(x.substring(0,3));
    }
}

输出:
hel

四、反转字符串

public class
test {
    public static void main(String[] args) {
        String test="hello world";
        System.out.println(new StringBuffer(test).reverse().toString());
    }
}

五、去除字符串首位的空格

public class
test {
    public static void main(String[] args) {
        String test=" hello, world   ";
        System.out.println(test.trim());
    }
}

输出:
hello, world

六、部分替换字符串中的内容

public class
test {
    public static void main(String[] args) {
        String test="test code 1";
        StringBuilder sb=new StringBuilder(test);
        sb.replace(10,11,"new code");
        System.out.println(sb.toString());
    }
}

输出:
test code new code

七、String类和char数组的相互转化

7.1 char数组转化为String类

使用 String.valueOf(copyValueOf和valueOf的实现是完全相同的) 方法

public class
test {
    public static void main(String[] args) {
         char[] arr=new char[]{'t','e','s','t'};
         String str=String.valueOf(arr);
         System.out.println(str);
    }
}

输出:
test
7.2 String类转化为char数组
public class
test {
    public static void main(String[] args) {
         String str="test";
         char[] arr=str.toCharArray();
         for(int i=0;i<arr.length;i++){
             System.out.println(arr[i]);
         }
    }
}

输出:
t
e
s
t
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值