常用String方法大全

String方法:

  • 1.charAt(int index);

返回指定索引处的 char 值,下标从0计数

String s1 = "同一个明天";
System.out.println(s1.charAt(0));//运行结果:同
System.out.println(s1.charAt(2));//运行结果:个
  • 2.compareTo(String A_String);

将两个字符串进行比较,确定哪一个字符从字典顺序上来说更靠前。(当两个字符串都是大写字母或小写字母时,字典顺序与字母顺序相同)。如果该字符串在前,则返回一个负整数,如果两个字符串相等,那么返回零,如果String A_String在前,那么返回正整数。_该整数的绝对值就是对应Unicode字符编码的差值

//全是小写字母
String s2 = "abcd";
String s3 = "gbcd";
System.out.println(s2.compareTo(s3));//运行结果:-6

//全是大写字母
String s4 = "ABCD";
String s5 = "DEF";
System.out.println(s4.compareTo(s5));//运行结果:-3
//大小写字母比较
String s4 = "eBCD";
String s5 = "DEF";
System.out.println(s4.compareTo(s5));//运行结果:33.
//注意:在Unicode字符编码中:大写字母在小写字母的前面
  • 3.concat(A_String)

将指定字符串连接到此字符串的结尾。

String s6 = "I love you";
String s7 = ",Jack!";
System.out.println(s6.concat(s7));//运行结果:I love you,Jack!
  • 4.equals(Other_String)

将此字符串与指定的对象比较。返回值类型为boolean类型(若相等返回true,否则返回false)

String s8 = "I love you";
String s9 = "I love you";
String s10 = "i love you";
System.out.println(s8.equals(s9));//运行结果:true
System.out.println(s8.equals(s10));//运行结果:false

-5.equalsIgnoreCase(String anotherString)

将此 String 与另一个 String 比较,不考虑大小写。

String s11 = "I love you";
String s12 = "i love you";
System.out.println(s11.equalsIgnoreCase(s12));//运行结果:true
  • 6.indexOf(A_String)

返回指定字符在此字符串中第一次出现处的索引。

String s13 = "abcdef";
System.out.println(s13.indexOf("b"));//运行结果:1
  • 7.lastIndexOf(int ch)

返回指定字符在此字符串中最后一次出现处的索引。

String s14 = "aaas";
System.out.println(s14.lastIndexOf("a"));//运行结果:2
  • 8.length()

返回此字符串的长度。

String s15 = "asdfg";
System.out.println(s15.length());//运行结果:5
  • 9.toLowerCase()

使用默认语言环境的规则将此 String 中的所有字符都转换为小写。

String s16 = "ASDFG";
System.out.println(s16.toLowerCase());//运行结果:asdfg 
  • 10.toUpperCase()

使用默认语言环境的规则将此 String 中的所有字符都转换为大写。

String s17 = "asdfg";
System.out.println(s17.toUpperCase());//运行结果:ASDFG
  • 11.replace(char oldChar, char newChar)

返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

String s18 = "I hate you!";
System.out.println(s18.replace("hate","love"));//运行结果:I love you!
  • 12.substring(int beginIndex)
    substring(int beginIndex, int endIndex)

返回一个新的字符串,它是此字符串的一个子字符串。

String s19 = "abcdefghijk";
System.out.println(s19.substring(3));//运行结果:defghijk
System.out.println(s19.substring(1,5));//运行结果:bcde
  • 13.trim()

返回字符串的副本,忽略前导空白和尾部空白

String s20 = "  I love you Marry!  ";
System.out.println(s20.trim());//运行结果:I love you Marry!
  • 14.toCharArray()

将此字符串转换为一个新的字符数组。

String s21 = "abcdefghijk";
char[] c = s21.toCharArray();
for(int i = 0; i < s21.length();i++){
    	System.out.print(c[i] + " ");
   }

运行结果:
在这里插入图片描述

发布了5 篇原创文章 · 获赞 0 · 访问量 13

猜你喜欢

转载自blog.csdn.net/qianyuq/article/details/104902212