- equals()类的,返回的是boolean值,比较的是字符串的内容
boolean equals(Object anObject);
boolean contentEquals(StringBuffer sb);
boolean contentEquals(CharSequence cs);
boolean equalsIgnoreCase(String anotherString);boolean regionMatches(int toffset, String other, int ooffset,int len) //局部匹配
boolean regionMatches(boolean ignoreCase, int toffset,String other, int ooffset, int len) //局部匹配- compareTo()类
int compareTo(String anotherString);
int compareToIgnoreCase(String str);按字典顺序比较两个字符串。该比较基于字符串中各个字符的 Unicode 值 两个字符串不同的情况: * 在某个索引处的字符不同 * 长度不同 * 以上两种兼有
- 如 果它们在一个或多个索引位置上的字符不同,假设 k 是这类索引的最小值;则在位置 k 上具有较小值的那个字符串(使用 < 运算符确定),其字典顺序在其他字符串之前。在这种情况下,
compareTo返回这两个字符串在位置 k 处两个char 值的差,即值:this.charAt(k)-anotherString.charAt(k)
- 如果长度不同,
compareTo返回这两个字符串长度的差,即值:this.length()-anotherString.length()
- == 判断的是否是同一个对象
获取指定子字符串的最后一次出现的位置
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}用一个字符串替换另一个字符串中的子串
str.replaceFirst() // 替换匹配的第一个
str.replaAll() // 替换匹配的全部- 使用
StringBuffer(String string)方法缓冲输入String,反转缓冲区,然后使用toString()方法将缓冲区转换成String。
String reverse = new StringBuffer(string).reverse().toString();- 手动实现 先把String转化为charArray数组,再从数组的最后到第一个依次输出
String str1 = "www.baidu.com";
char[] chars = str1.toCharArray();
for (int i=chars.length-1;i>=0;i--){
System.out.print(chars[i]);
}indexOf()方法在String对象中搜索单词,该方法返回字符串中的单词的位置索引(如果找到)值。 否则返回-1。str.indexOf();
contains()方法在String对象中搜索单词,若有该单词返回true,若无则返回falsestr.contains();
split(string)方法将字符串分割成多个子字符串
str.split(delimeter);使用String类的toUpperCase()方法将字符串的大小写更改为大写。
str.toUpperCase();regionMatches()方法确定两个字符串中的区域匹配。
public class StringRegionMatch {
public static void main(String[] args) {
String first_str = "Welcome to IBM";
String second_str = "I work with IBM";
boolean match = first_str.regionMatches(11, second_str, 12, 3);
System.out.println("first_str[11->14] == " + "second_str[12 -> 15]: "
+ match);
}
}以下是几个数字参数的说明:
- 11 - 是比较开始的源字符串中的索引号
- second_str - 是目标字符串
- 12是从目标字符串开始比较的索引号
- 3是要比较的字符数
执行上面示例代码,得到以下结果
first_str[11->14] == second_str[12 -> 15]: true