java Sting类函数

    技术2025-11-05  21

    一、判断字符串中是否包含某个字符串(字符): 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
    Processed: 0.018, SQL: 9