Java入门教程(31)——String类常用的方法

本文介绍了 Java 中 String 类的一些常用方法,包括字符提取、字符串长度获取、字符串比较(区分大小写与不区分大小写)、子字符串提取、字符串替换、转换为大写或小写、去除空白字符等功能,并通过示例代码演示了这些方法的具体使用。

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

String 类是我们最常使用的类。列出常用的方法。大家可以收藏一下,需要的时候回来看一下

在这里插入图片描述

实例

public class StringTest1 {
    public static void main(String[ ] args) {
        String s1 = "Hello World";
        String s2 = "hello world";
        System.out.println(s1.charAt(3));//提取下标为 3 的字符
        System.out.println(s2.length());//字符串的长度
        System.out.println(s1.equals(s2));//比较两个字符串是否相等
        System.out.println(s1.equalsIgnoreCase(s2));//比较两个字符串(忽略大小写)
        System.out.println(s1.indexOf("old"));//字符串 s1 中是否包含 Java
        System.out.println(s1.indexOf("apple"));//字符串 s1 中是否包含 apple
        String s = s1.replace(' ', '&');//将 s1 中的空格替换成&
        System.out.println("结果是:" + s);
    }
}


执行结果如下:

在这里插入图片描述

实例2:

public class StringTest2 {
    public static void main(String[ ] args) {
        String s = "";
        String s1 = "Where are you from?";
        System.out.println(s1.startsWith("Where"));//是否以 Where 开头
        System.out.println(s1.endsWith("from"));//是否以 from 结尾
        s = s1.substring(4);//提取子字符串:从下标为 4 的开始到字符串结尾为止
        System.out.println(s);
        s = s1.substring(4, 7);//提取子字符串:下标[4, 7) 不包括 7
        System.out.println(s);
        s = s1.toLowerCase();//转小写
        System.out.println(s);
        s = s1.toUpperCase();//转大写
        System.out.println(s);
        String s2 = " How old are you!! ";
        s = s2.trim();//去除字符串首尾的空格。注意:中间的空格不能去除
        System.out.println(s);
        System.out.println(s2);//因为 String 是不可变字符串,所以 s2 不变
    }
}

运行结果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员小凯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值