Java String类常用的方法


(1)int length():返回字符串的长度,例如:

String s1="hello";
System.out.println(s1.length());//显示为5

(2)char charAt(int index):获取字符串中指定位置的字符,index的取值范围是0~字符串长度-1,例如:

String s1="hello world",
System.out.println(s1.charAt(6));//显示结果为w

(3)int compareTo(String another):按Unicode码值逐字符比较两个字符串的大小。如果源串较小就返回一个小于0的值;两串相等返回0;否则返回大于0的值,例如:

System.out.println("hello".compareTo("Hello"));//显示-4
System.out.println("hello".compareTo("hello"));//显示0
System.out.println("Hello".compareTo("hello"));//显示1

(4)String concat(Striing str):把字符串str附加在当前字符串末尾,例如:

String str ="hello";
String str2="world";
System.out.println(str);//显示hello
System.out.println(Str2);//显示helloworld

(5)equals(Object obj)和equalsIgnoreCase(String str):判断两个字符串对象的内容是否相同。两者区别在于,equals()方法区分字母大小写,equalsIgnoreCase()不区分,例如:

String str1="hello";
String str2="Hello"
System.out.println(str1.equals(str2));//显示true
System.out.println(str1.equalsIgnoreCase(str2));//显示false

(6)int indexOf(int ch):返回指定字符ch在此字符串中第一次出现的位置。

int indexOf(String str):返回指定字符串str在此字符串中第一次出现的位置。

int lastIndexOf(int ch):返回指定字符ch在此字符串中最后一次出现的位置。

int lastIndexOf(String str):返回指定子字符串str在此字符串中最后一次出现的位置。

String str1="hello world";
System.out.pritnln(s1.indexOf("l"));//显示2
System.out.println(s1.indexOf("world"));//显示6
System.out.println(s1.lastIndexOf("l"));//显示9
System.out.println(s1.lastIndexOf("world"));//显示6

(7)String toUpperCase():将字符串转换为大写。

String toLowCase():将字符串转换成小写。例如:

String s1="Welcome to Java world";
System.out.println(s1.toUpperCase());//显示WELCOME TO JAVA WORLD
System.out.println(s1.toLowerCase());//显示welcome to java world

(8)String substring(int beginIndex):返回一个新字符串,改子字符串从指定索引处的字符开始,直到此字符串末尾。

String substring(int beginIndex,int endIndex):返回一个新字符串,改子字符串从指定的beginIndex处开始,直到索引endIndex-1处的字符。例如:

String s1="Welcome to Java world";
System.out.println(s4.substring(11));//显示Java world
System.out.println(s1.substring(11,15));//显示Java

(9)static String valueOf():把基本数据类型转换为String类型,例如:

int i=123;
String s1=String.valueOf(i);
System.out.println(s1);//显示字符串123

(10)String[] split(String regex):将一个字符串按照指定的分隔符分隔,返回分隔符后的字符串数组。


原文链接:https://www.cnblogs.com/liangmingda/p/13462834.html