String中有很多方法,在处理字符串问题时用到,现在整理如下:
1、charAt根据索引查找并返回索引处的字符
char | charAt(int index)
Returns the char value at the specified index.
|
int | compareTo(String anotherString)
Compares two strings lexicographically.
|
String | concat(String str)
Concatenates the specified string to the end of this string.
|
byte[] | getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
|
byte[] | getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
|
int | indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
|
int | indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
|
int | indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
|
int | indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
|
int | length()
Returns the length of this string.
|
String[] | split(String regex)
Splits this string around matches of the given regular expression.
|
String | substring(int beginIndex)
Returns a string that is a substring of this string.
|
String | substring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.
|
9、valueOf,静态方法,将参数转换为字符串返回,有重载
static String | valueOf(boolean b)
Returns the string representation of the boolean argument.
|
public static void main(String[] args){
String s1="abcdefgde";
System.out.println(s1.charAt(1));//输出 b
String s2="azqrst";
System.out.println(s1.compareTo(s2));//输出-24
System.out.println(s1.concat(s2));//输出abcdefazqrst
System.out.println(s1);//输出adcdef
System.out.println(s1.getBytes());
System.out.println(s1.indexOf("d"));//3
System.out.println(s1.indexOf("d",2));//3
System.out.println(s1.indexOf("def"));//3
System.out.println(s1.lastIndexOf("d"));//7
System.out.println("abcdedfd".split("d").length);//3
System.out.println("abcddedfd".split("d").length);//4
System.out.println(s1.substring(2,5));//cde
System.out.println(String.valueOf(true));//true
}
还有很多其他方法,后边用到继续补充。