java操作字符串的常用方法

字符串查找

String提供了两种查找字符串的方法,即indexOf与lastIndexOf方法。

1、indexOf(String s)
该方法用于返回参数字符串s在指定字符串中首次出现的索引位置,当调用字符串的indexOf()方法时,会从当前字符串的开始位置搜索s的位置;如果没有检索到字符串s,该方法返回-1

String str ="We are students";
int size = str.indexOf("a"); // 变量size的值是3

2、lastIndexOf(String str)
该方法用于返回字符串最后一次出现的索引位置。当调用字符串的lastIndexOf()方法时,会从当前字符串的开始位置检索参数字符串str,并将最后一次出现str的索引位置返回。如果没有检索到字符串str,该方法返回-1.

如果lastIndexOf方法中的参数是空字符串"" ,,则返回的结果与length方法的返回结果相同。
String str ="We are students";
int size = str.lastIndexOf("e"); // 变量size的值是11

获取指定索引位置的字符

通过String类的substring()方法可对字符串进行截取。这些方法的共同点就是都利用字符串的下标进行截取,且应明确字符串下标是从0开始的。在字符串中空格占用一个索引位置。

1、substring(int beginIndex)
该方法返回的是从指定的索引位置开始截取知道该字符串结尾的子串。

 String str = "Hello word";
 String substr = str.substring(3); //获取字符串,此时substr值为lo word

2、substring(int beginIndex, int endIndex)
beginIndex : 开始截取子字符串的索引位置
endIndex:子字符串在整个字符串中的结束位置

String str = "Hello word";
String substr = str.substring(0,3); //substr的值为hel

去除空格

trim()方法返回字符串的副本,忽略前导空格和尾部空格。

String str = " Hello word ";
String substr = str.trim(); //substr的值为Hello word

字符串替换

replace(char oldChar,char newChar)方法可实现将指定的字符或字符串替换成新的字符或字符串

oldChar:原字符
newChar: 新字符

public class Test {
    public static void main(String args[]) {
        String Str = new String("hello");

        System.out.print("返回值 :" );
        System.out.println(Str.replace('o', 'T'));//返回值 :hellT

        System.out.print("返回值 :" );
        System.out.println(Str.replace('l', 'D'));//返回值 :heDDo
    }
}

字符串分割

split(String regex, int limit) 方法可以使字符串按指定的分隔字符或字符串对内容进行分割,并将分割后的结果存放在字符数组中。

regex :正则表达式分隔符。
limit : 分割的份数。

public class Test {
    public static void main(String args[]) {
        String str = new String("Welcome-to-Runoob");
 
        System.out.println("- 分隔符返回值 :" );
        for (String retval: str.split("-")){
            System.out.println(retval);
        }
 
        System.out.println("");
        System.out.println("- 分隔符设置分割份数返回值 :" );
        for (String retval: str.split("-", 2)){
            System.out.println(retval);
        }
 
        System.out.println("");
        String str2 = new String("www.runoob.com");
        System.out.println("转义字符返回值 :" );
        for (String retval: str2.split("\\.", 3)){
            System.out.println(retval);
        }
 
        System.out.println("");
        String str3 = new String("acount=? and uu =? or n=?");
        System.out.println("多个分隔符返回值 :" );
        for (String retval: str3.split("and|or")){
            System.out.println(retval);
        }
    }
}
//以上程序的输出结果
	- 分隔符返回值 :
	Welcome
	to
	Runoob

	- 分隔符设置分割份数返回值 :
	Welcome
	to-Runoob

	转义字符返回值 :
	www
	runoob
	com

	多个分隔符返回值 :
	acount=? 
 	uu =? 
 	n=?

字母大小写转换

字符串的toLowerCase()方法可将字符串中的所有字符从大写字母改写为小写字母,而tuUpperCase()方法可将字符串中的小写字母改写为大写字母。

 String str ="We";
 str.toLowerCase();
 str.toUpperCase();

猜你喜欢

转载自blog.csdn.net/zch15779080212/article/details/84756265