String类方法详解

String中有很多方法,在处理字符串问题时用到,现在整理如下:

1、charAt根据索引查找并返回索引处的字符

char charAt(int index)
Returns the char value at the specified index.
2、compareTo,将字符串this与参数字符串进行每个字符比较,如果this字符串的字符依据字母排序表在参数字符串之间,返回负值,其实就是字符转换为整形的差值。为0说明两字符串相等

int compareTo(String anotherString)
Compares two strings lexicographically.
3、将字符串进行拼接并返回,this和参数字符串没有变化

String concat(String str)
Concatenates the specified string to the end of this string.
4、getBytes,将字符串进行编码,返回编码字节序列,可以指定编码规则,utf-8,ISO-8859-1等

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.
5、indexOf,返回字符串第一次出现某个字符,或子字符串时的位置,如果不存在返回-1;lastIndexOf是最后一次出现的位置
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.
6、length()返回字符串的大小

int length()
Returns the length of this string.
7、split,根据参数,将字符串拆分成字符数组,当两个regex靠着时,会出现一个空字符串

String[] split(String regex)
Splits this string around matches of the given regular expression.
8、subString,根据索引返回子字符串,注意两个索引时,后一个为endIndex,而不是长度,且不包含后一个索引指向的值

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
		
	} 


还有很多其他方法,后边用到继续补充。


你可能感兴趣的:(String)