String类在实际的工作中使用非常广泛,String类提供了一系列的功能操作方法,这些方法可以通过Java Doc文档查阅。
1.charAt()取出指定索引的字符:
String str="hello";
char c=str.charAt(0);
System.out.println(c); //程序执行结果:h
2、检测两个字符串是否相等,一定不要用 ==(内存位置相同) 来判断,用equals(值相等)如下例所示,返回值为 false
if(str.substring(2) == "ring"){
System.out.println("True");
}
else{
System.out.println("false");
}
3、String substring(int beginIndex):返回指定起始位置至字符串末尾的字符串
substring(int beginIndex, int endIndex):返回指定起始位置(含)到结束位置(不含)之间的字符串
System.out.println("String.substring:" +str.substring(str.offsetByCodePoints(0, 2)));
//return "String.substring:ring";
System.out.println("String.substring:" +str.substring(str.offsetByCodePoints(0, 2), str.offsetByCodePoints(0, 2)+1));
//return "String.substring:r";
4、boolean equals(Object other):如果字符串与other相等返回true,否则返回false
boolean equalsIgnoreCase(String other):如果字符串与other相等(忽略大小写)返回true,否则返回false
System.out.println("String.equals:" +str.equals("string"));
//return "String.equals:false";
System.out.println("String.equalsIgnoreCase:" +str.equalsIgnoreCase("string"));
//return "String.equalsIgnoreCase:true";
5、int indexOf(String str):返回指定字符串的索引位置
int indexOf(String str, int fromIndex):返回从指定索引位置fromIndex开始的str的索引位置,如果没有返回-1
int indexOf(int cp):cp----ASCII码对应的十进制码
int indexOf(int cp, int fromIndex):----ASCII码对应的十进制码,formIndex字符串索引起始位置-----返回从指定索引位置fromIndex 开始的str的索引位置,如果没有返回-1
System.out.println("String.indexOf:" +str.indexOf("i"));
//return "String.indexOf:3";
System.out.println("String.indexOf:" +str.indexOf("i", 1));
//return "String.indexOf:3";
System.out.println("String.indexOf:" +str.indexOf("i", 4));
//return "String.indexOf:-1";
System.out.println("String.indexOf:" + str.indexOf(83));//83:S
//return "String.indexOf:0";
System.out.println("String.indexOf222:" + str.indexOf(110,0));//110:n
//return "String.indexOf:4";
6、String replace(CharSequence oldString, CharSequencenewString):用newString替换字符串中的oldString
System.out.println("String.replace:" + str.replace("g","gs"));
//return "String.replace:Strings";
7.split 方法:将一个字符串分割为子字符串,然后将结果作为字符串数组返回。 stringObj.split([separator],[limit])
8.contains:“当且仅当此字符串包含指定的 char 值序列时,返回 true”即对于指定的字符串要完全匹配,不可以有额外的字符.
public static void main(String[] args){
String s = "my String is s";
boolean result1 = s.contains("myname");
boolean result2 = s.contains("myis");
boolean result3 = s.contains("myString");
System.out.println("result1 is"+result1+
"; result2 is"+result2+"; result3 is "+result3);
}
结果:result1 is false; result2 is false; result3 is true