Java之String类--(2)常用方法

Java中的String类有很多常用的方法,我们来分别介绍一下
(一)
1、public char charAT(int index):返回字符串中的第index个字符
2、public int length():返回字符串的长度
3、public int indexOf(String str):返回字符串中出现str的第一个位置
4、public int indexOf(String str,int fromIndex):饭后字符串中从fromIndex开始出现str的第一个位置
5、public boolean equalsIgnoreCase(String another):比较字符串与another是否一样(忽略大小写)
6、public String replace(char oldChar,char newChar):在字符串中用newChar替换oldChar字符

我们来用一段代码测试一下

public class TestString2 {
    public static void main(String[] args) {
        String str1 = "sun java" ;      String str2 = "Sun Java" ;
        System.out.println(str1.charAt(1));             //u
        System.out.println(str2.length());              //8
        System.out.println(str1.indexOf("java"));           //4
        System.out.println(str1.indexOf("Java"));           //-1
        System.out.println(str1.equals(str2));                          //false
        System.out.println(str1.equalsIgnoreCase(str2));        //true

        String s = "我是程序员,我在学Java";
        String s1 = s.replace('我','你');
        System.out.println(s1);                                         //你是程序员,你在学Java
    }
}

(二)
7、public boolean startsWith(String prefix):判断字符串是否以prefix字符开始
8、public boolean endsWith(String prefix):判断字符串是否以prefix字符结束
9、public String toUpperCase():返回一个字符串为该字符串的大写形式
10、public String toLowerCase():返回一个字符串为该字符串的小写形式
11、public String substring(int beginIndex):返回字符串从beginIndex开始到结尾的子字符串
12、public String substring(int beginIndex,int endIndex):返回字符串从beginIndex开始到endIndec结尾的子字符串
13、public String trim():返回将该字符串去掉开头和结尾空格后的字符串

同样用一段代码来说明

public class TestString3 {
    public static void main(String[] args) {
        String s = "Welcome to Java world";
        String str = "   Hello World   ";
        System.out.println(s.startsWith("welcome"));                //false
        System.out.println(s.startsWith("Welcome"));                //true

        System.out.println(s.endsWith("World"));                //false
        System.out.println(s.endsWith("world"));                //true

        System.out.println(s.toUpperCase());                        //WELCOME TO JAVA WORLD
        System.out.println(s.toLowerCase());                        //welcome to java world

        System.out.println(s.substring(11));                        //Java world
        System.out.println(s.substring(11,14));                 //Java

        System.out.println(str.trim());                                 //Hello World
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值