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
		
	} 


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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值