最近在自学java,正在阅读《Java的核心技术卷1》,看到String类的方法随手将其自己整理下来,
顺便加深一下自己的记忆
String类
char charAt(int index) 返回index处的字符
String string=new String("abc");
System.out.println(string.charAt(1)); //运行结果为b
int compareTo(String other) 按照字典顺序,如果字符串位于 other 之前,返回一个负数;如果字符串位于 other 之 后,返回一个正数;如果两个字符串相等,返回 0。
String s1="abc";
String s2="abd";
System.out.println(s1.compareTo(s2)); //运行结果为-1
boolean equals(String other) 如果字符串与 other 相等, 返回 true,否则返回false
String s1="abc";
String s2="abc";
System.out.println(s1.equals(s2)); //运行结果为true
boolean equalsIgnoreCase(String s)如果在忽略大小写的情况下,原String与s逐字符比较都相等,则返回true。
String s1="abc";
String s2="ABC";
System.out.println(s1.equals(s2)); //运行结果为true
boolean startsWith(String s )
boolean endsWith(String s ) 如果字符串以 s开头或结尾, 则返回 true。
String s1="abc";
String s2="abc";
System.out.println(s1.startsWith("ab")); // 运行结果为 ture
System.out.println(s2.endsWith("b")); // flase
int indexOf(String s) 返回串中第一次出现s串的序号值
String s1="abcd";
System.out.println(s1.indexOf("cd")); //运行结果为2 (“cd”串第一次是出现在2这个位置)
int lastIndexOf(String s) 返回串中最后一次出现s串的序号值,如果没有找到就返回-1
String s1="abcd abcd";
System.out.println(s1.lastIndexOf("bcd"));
System.out.println(s1.lastIndexOf("xyz")); // 运行结果为 6 -1
String concat(String s) 返回一个串,在原串的基础上添加上s串
String s1="hello";
System.out.println(s1.concat(" world"));//运行结果为 hello world
String replace(String old, String new) 将原来串中的所有old串替换成new串
String s1="hello";
System.out.println(s1.replaceFirst("ll", "r"));//运行结果为 hero
String substring(int start, int end) 原串中截取start开始到end结束的一段字串并返回
如果此处不给end参数就从start开始截取到串尾
String s1="hello";
System.out.println(s1.substring(0, 3));//运行结果为 hel
String toLowerCase() 返回一个新的String,它将原来的String中的大写字母变成小写。
String toUpperCase() 返回一个新的String,它将原来的String中的小写字母变成大写。
int length( ) 返回字符串的长度
String trim( ) 返回一个新字符串。这个字符串将删除了原始字符串头部和尾部的空格
String join(CharSequence delimiter, CharSequence… elements) 返回一个新字符串, 用给定的定界符连接所有元素。
System.out.println(String.join("\\", "c","Program Files","java","JDK 12.0"));
运行结果为 c\Program Files\java\JDK 12.0