java编程基础:String字符串的相关操作方法

常用方法:
1, char charAt(int index) 获取指定索引位置的char值

public class Test {
    public static void main(String args[]) {
        String s = "www.runoob.com";
        char result = s.charAt(6);
        System.out.println(result);
    }
}

以上程序执行结果为:
n

2,String concat(String str)将指定字符串连接到改字符串结尾

public class Test {
    public static void main(String args[]) {
        String s = "菜鸟教程:";
        s = s.concat("www.runoob.com");
        System.out.println(s);
    }
}

以上程序执行结果为:
菜鸟教程:www.runoob.com

3, boolean endsWith(String suffix)测试该字符串是否以指定后缀结尾

4,String toUpperCase()小写转大写

5, String toLowerCase()转小写

6,String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
返回一个新`字符串,它是此字符串的一个子字符串。

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.runoob.com");
 
        System.out.print("返回值 :" );
        System.out.println(Str.substring(4) );
 
        System.out.print("返回值 :" );
        System.out.println(Str.substring(4, 10) );
    }
}

以上程序执行结果为:
返回值 :runoob.com
返回值 :runoob

7, String[] split(String regex)
String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。

8, char[] toCharArray()
将此字符串转换为一个新的字符数组。
regex – 匹配此字符串的正则表达式。
newChar – 用来替换每个匹配项的字符串。

public class Test {
    public static void main(String args[]) {
        String Str = new String("www.google.com");

        System.out.print("匹配成功返回值 :" );
        System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" ));
        System.out.print("匹配失败返回值 :" );
        System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" ));
    }
}

以上程序执行结果为:
匹配成功返回值 :runoob
匹配失败返回值 :www.google.com

9, int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。

10, int compareTo(Object o)
把这个字符串和另一个对象比较。

public class Test {
 
    public static void main(String args[]) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";
 
        int result = str1.compareTo( str2 );
        System.out.println(result);
      
        result = str2.compareTo( str3 );
        System.out.println(result);
     
        result = str3.compareTo( str1 );
        System.out.println(result);
    }
}

以上程序执行结果为:
0
-3
3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值