Java里String的方法

本文详细介绍Java中字符串的各种操作方法,包括长度获取、字符定位、数组转换、比较、开头与结尾判断、分隔、连接、子串提取、替换等功能,是Java开发者必备的实用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**1.length() 获取字符串长度 **

String str="abc";
int n=str.length();
System.out.println(n)

2.charAt(int n) 定位n下标的字母

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWord";
        System.out.println(a.charAt(2));
    }
}

结果显示: l

3.tocharArray() 将字符串变成一个字符数组

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWord";
        char[] Array = a.toCharArray();
        System.out.println(Arrays.toString(Array));
        }
 }

输出结果:[H,e,l,l,o,W,o,r,d]
4.equals()和equalsIngoreCase() 比较两个字符串是否相等,前者区分大小写,后者不区分大小写

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWorld";
        String b="helloworld";
        boolean t=a.equals(b);
        boolean h=a.equalsIgnoreCase(b);
        System.out.println(t);
        System.out.println(h);
        }
 }

输出结果: false true

5.startsWith()和endsWith()判断字符串是不是以特定的字符开头或结束

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWorld";
        boolean t=a.startsWith("b");
        boolean h=a.endsWith("d");
        System.out.println(t);
        System.out.println(h);
        }
   }

输出结果:false true

6.spilt() 分隔字符串

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWorld";
        String[] s1=a.split("W");
        System.out.println(s1[0]);
        System.out.println(s1[1]);
        }
 }

输出结果:Hello orld

7.concat 连接字符串

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWorld";
        String b="你好啊";
        String s=b.concat(a);
        System.out.println(s);
        }
  }

输出结果:你好啊HelloWorld

8.subString(int startindex,int endindex) 按初始下标和结束下标分隔字符串

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWorld";
        String str1=a.substring(0,5);
        String str2=a.substring(5,a.length());
        System.out.println(str1);
        System.out.println(str2);
        }
 }

输出结果:Hello World

9.replace() 替换字符串

public class TestDemo2 {
    public static void main(String[] args) {
        String a="HelloWorld";
        String b=a.replace("lo","ph");
        System.out.println(b);
        }
 }

输出结果:HelphWorld

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值