java字符串处理(split,substring,indexof)方法介绍



java中字符串处理(split,substring,indexof)

1.类String中提供了length( )、charAt( )、indexOf( )、lastIndexOf( )、getChars( )、getBytes( )、toCharArray( )等方法。

◇ public int length() 此方法返回字符串的字符个数
◇ public char charAt(int index) 此方法返回字符串中index位置上的字符,其中index 值的 范围是0~length-1
◇ public int indexOf(int ch)
public lastIndexOf(in ch)

返回字符ch在字符串中出现的第一个和最后一个的位置
◇ public int indexOf(String str)
public int lastIndexOf(String str)
返回子串str中第一个字符在字符串中出现的第一个和最后一个的位置
◇ public int indexOf(int ch,int fromIndex)
public lastIndexOf(in ch ,int fromIndex)
返回字符ch在字符串中位置fromIndex以后出现的第一个和最后一个的位置
◇ public int indexOf(String str,int fromIndex)
public int lastIndexOf(String str,int fromIndex)
返回子串str中的第一个字符在字符串中位置fromIndex后出现的第一个和最后一个的位置。
◇ public void getchars(int srcbegin,int end ,char buf[],int dstbegin)
srcbegin 为要提取的第一个字符在源串中的位置, end为要提取的最后一个字符在源串中的位置,字符数组buf[]存放目的字符串,    dstbegin 为提取的字符串在目的串中的起始位置。
◇public void getBytes(int srcBegin, int srcEnd,byte[] dst, int dstBegin)
参数及用法同上,只是串中的字符均用8位表示。
2.String的substring方法。
substring(参数)是java中截取字符串的一个方法
有两种传参方式
一种是public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
另一种是public String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex – 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。

3.split函数进行分割字符串
(1)
String s=”qqqqqqwwwwwrttgtggggtthyhyhyhyhyhyhtbvhnmjk,kttyjuuju”;
String[] sa=s.split(“t”);
for (String ss : sa) {
System.out.println(ss);
}
System.out.println(sa.length);
运行结果:
qqqqqqwwwwwr
g
gggg

hyhyhyhyhyhyh
bvhnmjk,k

yjuuju
10
总结:split以设定的字符进行截断操作。输出结果不会显示这个字符。但是它会以”"串的形式存在。
(2)
String s=”qqqqqqwwwwwrtttgtggggtthyhyhyhyhyhyhtbvhnmjk,kttyjuuju”;
String[] sa=s.split(“/t”);
for (String ss : sa) {
System.out.println(ss);
}
System.out.println(sa.length);
运行结果
qqqqqqwwwwwrtttgtggggtthyhyhyhyhyhyhtbvhnmjk,kttyjuuju
1
总结:如果给的字符串中没有这个字符,那么后打印出所有的字符串