天天看点

java字符串处理常用函数(数字型和字符串转换,字符串拆分、查找、截取)

一、字符串转化成数字型

String   s   =   "123.456 ";  //要确保字符串为一个数值,否则会出异常

double   d   =   Double.parseDouble(s); 

float   f   =   Float.parseFloat(s);

String   s   =   "123 "; 

int i = Integer.parseInt(s);

二、数字型转化成字符串

方法一:直接强制转换。如:String  str= (String)123;

方法二:直接通过空字符串+数字的形式转换为字符串(前后都可以用)。如:String str= ""+123;

方法三:直接通过包装类来实现。如:String  str = String.valueOf(123456);

三、字符串拆分

 String类下的split方法,可以按照指定的定界字符串,对某一字符串进行分割,将待分割字符串中参考字符串前后的字符串提取出来,作为返回值。返回类型为String中,维度由分割完成的结果决定,但内容中会直接去掉定界字符串。定界字符串查找不到时返回结果为该字符串本身。 需要注意的是定界字符串本质上是正则表达式,如果参考字符串中包含有特殊含义的符号,需要进行转义。

String a = "abcdefgabcdefgabcdefg";  

String b[] = a.split("a");  

for(inti = 0; i<b.length; i++)  

    System.out.println(b[i]);  

    运行结果为:

bcdefg  

bcdefg  

bcdefg  

String a = "abcdefgabcdefgabcdefg";  

String b[] = a.split("a",2);  

for(int i = 0; i<b.length; i++)  

  System.out.println(b[i]);  

   运行结果为:

bcdefgabcdefgabcdefg  

 即split第二个参数用来限制分割完成的字符串段数,分割由左到右进行,缺省则代表分割段数不限,直至分割完成为止。

四、字符串查找

  String类下的lastIndexOf方法,用于在当前字符串中查找指定字符串。

  1、int lastIndexOf(String arg0) 和 int lastIndexOf(int arg0)

    用于查找当前字符串中指定字符串或字符(int arg0表字符的ascii码值)最后出现的位置,返回值为子串在原串中的相对位置,若找不到,则返回-1。 

    看例子:

String s = "abcdefgabcdefg";  

int i = s.lastIndexOf("cd");  

System.out.println(i);  

   运行结果为:

          9  

    需要注意的是字符串s中共有两个”cd”子串,本函数返回的是最后一个子串的位置。

  2、int lastIndexOf(String arg0, int arg1) 和int lastIndexOf(int arg0, int arg1)

    在当前字符串中小于arg1的范围中,查找指定字符串或字符。返回值同样为子串在原串中最后一次出现的相对位置,只不过查找有范围限制,超出范围的部分即便仍有子串,也无法找到。

    看例子:

String s = "abcdefgabcdefg";  

int i = s.lastIndexOf("cd",8);  

System.out.println(i);  

运行结果为:

2  

    注意与上一个例子做比较。

    但是当范围当中包含了子串的前面的某一位或某几位时:

String s = "abcdefgabcdefg";  

int i = s.lastIndexOf("cd",9);  

System.out.println(i);  

运行结果为:

9  

    原因很简单,字符串比较时约束的范围仅限制住了首地址而没有约束长度。

  与lastIndexOf方法相对的indexOf方法。

  1、Int indexOf(String arg0)和Int indexOf(int arg0)

    这两个方法返回值为源字符串中子串最先出现的位置(参数int arg0同样指字符的ascii码值),若找不到,则返回-1。

    与上文lastIndexOf对比:

String s = "abcdefgabcdefg";  

int i = s.indexOf("cd");          

System.out.println(i);  

运行结果为:

2  

 2、 int indexOf(String arg0, int arg1) 和int indexOf(int arg0, int arg1) 

    这两个方法返回值为从指定位置起查找,子串最先出现的位置,若找不到,则返回-1。与lastIndexOf相区别的是indexOf的限制arg1参数限定的是由此位起始搜索,lastIndexOf限定的是搜索到此位为止。

则:

String s = "abcdefgabcdefg";  

int i = s.indexOf("cd",8);       

System.out.println(i);  

运行结果为:

9  

  String substring(int arg0)与String substring(int arg0, int arg1)

  这两个函数用来在源字符串中根据指定位置取出子串。前者返回源字符串中从参数arg0指定的位置开始至字符串结尾的子串;后者返回源字符串中位置arg0到位置arg1指定的子串。

  substring可与上文中的查找方法一起使用,用于提取指定字符串。

看例子:

         String s = "abcdefgabcdefg";  

String cd = "cd";  

String s1 = s.substring(s.indexOf(cd));  

String s2 = s.substring(s.indexOf(cd), s.indexOf(cd)+cd.length());  

System.out.println(s1);  

System.out.println(s2);  

运行结果为:

cdefgabcdefg  

cd  

注意当参数越界时会抛出Java.lang.StringIndexOutOfBoundsException异常。