String一些函数的用法

来源:互联网 发布:mac dashboard插件 编辑:程序博客网 时间:2024/05/20 17:07


1、substring()用法:这个函数返回第一个参数中从第二个参数指定的位置开始、第三个参数指定的长度的子字符串。
该字符串中的每个字符都被认为具有数字位置:第一个字符的位置是 1,第二个字符的位置是 2,依此类推。


如果未指定第三个参数,将返回从第二个参数指定的位置开始直到字符串结尾的子字符串。


如果参数不是字符串类型,将先使用 string() 函数转换为字符串,然后计算该转换的结果。


如:以下函数调用返回“234”: substring("12345",2,3) 
public class StringTest {


public static void main(String[] args) {
// TODO Auto-generated method stub
String str="acdeedsjkeedjdjeejkdjdee";

sop("count="+getSubCount(str,"ee"));

}
public static int getSubCount(String str,String key)
{
int count=0;
int index=0;

while((index=str.indexOf(key))!=-1)
{
sop("str="+str);
str=str.substring(index+key.length());

count++;
}
return count;
}
public static void sop(String str)
{
System.out.println(str);
}
}


2、int indexOf(String str):返回字符中indexof(string)中字串string在父串中首次出现的位置,从0开始!
没有返回-1;方便判断和截取字符串!
3、int length();获取长度。
4、int charAt(int index):根据位置获取某个位置上的字符。
5、int indexOf(String str,int fromIndex):返回指定字符串str第一次出现的索引,从指定的索引开始搜索。
public class StringTest {


public static void main(String[] args) {
// TODO Auto-generated method stub
String str="acdeedsjkeedjdjeejkdjdee";

sop("count="+getSubCount_2(str,"ee"));

}
public static int getSubCount(String str,String key)
{
int count=0;
int index=0;

while((index=str.indexOf(key))!=-1)
{
sop("str="+str);
str=str.substring(index+key.length());

count++;
}
return count;
}
public static int getSubCount_2(String str,String key)
{
int count=0;
int index=0;

while((index=str.indexOf(key,index))!=-1)
{
sop("index="+index);
index=index+key.length();
count++;
}
return count;
}
public static void sop(String str)
{
System.out.println(str);
}
}


6、int indexOf(int ch,int fromIndex):返回指定字符ch第一次出现的索引,从指定的索引开始搜索。
0 0
原创粉丝点击