---
title: "JAVA-字符串String常用方法"
author: "韬光养晦"
date: "2011-10-22T22:39:08Z"
tags: []
categories: ["编程语言"]
slug: "java-string"
draft: false
lastmod: "2011-10-22T22:39:08Z"
id: 1207907
url: "https://taohui.iteye.com/blog/1207907"
---

**String类  常用方法**

**1、字符串与字符数组之间的转换：**

字符串转为字符数组：public char\[] toCharArray()

字符数组转为字符串:public String(char\[] value)

                  PublicString(char\[] value,int offset,int count)

例:

public class StringAPIDemo01{

       public static void main(String args\[]){

              String str1 = "hello" ;                  // 定义字符串

              char c\[] = str1.toCharArray() ;      // 将一个字符串变为字符数组

              for(int i=0;i&lt;c.length;i++)     // 循环输出

                {System.out.print(c\[i] + "、") ; }

              System.out.println("") ;        // 换行

              String str2 = new String(c) ;  // 将全部的字符数组变为String

              String str3 = new String(c,0,3) ;   // 将部分字符数组变为String

              System.out.println(str2) ;             // 输出字符串

              System.out.println(str3) ;             // 输出字符串

       }

};

 

 

 

 

**2、字符串与字节数组之间的转换：**

字符串转字节数组：public byte\[] getBytes()

字符数组转字符串：public String(byte\[] bytes)

                  public String(byte\[] bytes,int offset,int length)

例：

public class StringAPIDemo02{

       public static void main(String args\[]){

              String str1 = "hello" ;                  // 定义字符串

              byte b\[] = str1.getBytes() ;    // 将字符串变为byte数组

              System.out.println(new String(b)) ;      // 将全部的byte数组变为字符串

              System.out.println(new String(b,1,3)) ;       // 将部分的byte数组变为字符串

       }

};

 

 

 

 

 

**3、字符串与整型数组间的转换：**

public class StringAPIDemo03

{public static void main(String\[] args)

       {//字符串转为整型数组：

     String s1="123456789";

     int n1\[]=new int\[s1.length()];

     for(int i=0;i&lt;n1.length;i++)

         n1\[i]=Integer. parseInt(String.valueOf(s1.charAt(i)));

 

    //整型数组转为字符串：

    int n2\[]={1,2,3};

    String s2="";

    for(int i=0;i&lt;n2.length;i++)

    s2+=Integer.toString(n2\[i]);

    System.out.println(s2);

       }

}

 

 

 

 

**4、获取给定的Index处的字符：**

char charAt(int index)

 

例：

public class StringAPIDemo04{

       public static void main(String args\[]){

              String str1 = "java" ;                   // 定义String对象

              System.out.println(str1.charAt(3)) ;     // 取出字符串中第四个字符’a’

       }

};

 

 

 

 

 

 

 

 

 

 

 

**5、按字典顺序比较两个字符串。**

int compareTo(String anotherString)   //区分大小写

int compareToIgnoreCase(String str)   //不区分大小写

 

例：

public class StringAPIDemo05

{public static void main(String\[] args)

       {String s1="abc";

        String s2="aBc";

        //A的Unicode码为65，a的Unicode码为97，所以A&lt;a

        if(s1.compareTo(s2)&gt;0)

           System.out.println("s1&gt;s2");

     if(s1.compareTo(s2)==0)

           System.out.println("s1==s2");

        if(s1.compareTo(s2)&lt;0)

        System.out.println("s1&lt;s2");

       }

}

 

 

 

 

**6、将此字符串与指定的对象比较：**

boolean equals(Object anObject)  考虑大小写

boolean equalsIgnoreCase(String anotherString)  不考虑大小写

 

例：

public class StringAPIDemo06

{public static void main(String\[] args)

       {

        String s1 = "abcd";

        String s2 = "Abcd";

     System.out.println("s1是否等于s2:"+s1.equals(s2));            //false

     System.out.println("s1是否等于s2:"+s1.equalsIgnoreCase(s2));   //true

       }

}

 

 

 

 

 

 

**7、将指定字符串连接到此字符串的结尾：**

String concat(String str)

 

例：

public class StringAPIDemo07

{public static void main(String\[] args)

       {String s1="abc";

        String s2="def";

     System.out.println(s1.concat(s2));

        //输出：abcdef

       }

}

 

 

 

 

**8、copyValueOf返回指定数组中表示该字符序列的String：**

String copyValueOf(char\[] data)  

`data` - 字符数组；  返回：一个 String，它包含字符数组的字符。

 

String copyValueOf(char\[] data, int offset, int count)

data - 字符数组。offset - 子数组的初始偏移量。count - 子数组的长度；返回：一个 String，它包含字符数组的指定子数组的字符。

 

例：

public class StringAPIDemo08

{public static void main(String\[] args)

  {

   char\[] c=new char\[]{'a','b','c','d'};

   System.out.println(String.copyValueOf(c));

   /\*返回有c中所有元素构成的字符串，相当于String s=new String(c);

   结果就是产生一个 "abcd "字符串\*/

 

   System.out.println(String.copyValueOf(c,2,2));

   /\*返回由c中从下标2的元素（就是 'c '）开始，长度为2的元素构成的字符串，

   结果就是产生一个 "cd "字符串。\*/

   }

}

 

 

 

 

**9、startsWith与endsWith：**

boolean startsWith(String prefix)   测试此字符串是否以指定的前缀开始

boolean endsWith(String suffix)    测试此字符串是否以指定的后缀结束

例：

public class StringAPIDemo09

{public static void main(String\[] args)

       {

        String str1 = "\*\*HELLO" ;                // 定义字符串

        String str2 = "HELLO\*\*" ;                // 定义字符串

        if(str1.startsWith("\*\*"))                    // 判断是否以“\*\*”开头

              {System.out.println(str1+"以\*\*开头") ;}

        if(str2.endsWith("\*\*"))              // 判断是否以“\*\*”结尾

              {System.out.println(str2+"以\*\*结尾") ;}

       }

}

 

 

 

 

 

 

**10、大小写字母间的转换：**

String toLowerCase()  将 String 中的所有字符都转换为小写

String toUpperCase()  将 String 中的所有字符都转换为大写

例：

public class StringAPIDemo10

{public static void main(String\[] args)

       {

        String s1 = "Hello";

     System.out.println(s1.toLowerCase());//hello

     System.out.println(s1.toUpperCase());//HELLO

       }

}

 

 

 

 

 

 

 

 

 

**11、indexOf返回指定字符（字符串）索引：**

**int indexOf(char ch||String str)**   返回指定字符(字符串)在此字符串中第一次出现处的索引

 

**int indexOf(char ch||String str, int fromIndex)**  返回在此字符串中第一次出现指定字符(字符串)处的索引，从指定的索引开始搜索

 

**int lastIndexOf(char ch||String str)**  返回指定字符(字符串)在此字符串中最后一次出现处的索引

 

**int lastIndexOf(char ch||String str,int fromIndex)** 返回指定字符(字符串)在此字符串中最后一次出现处的索引，从指定的索引处开始进行反向搜索

 

例：

public class StringAPIDemo11

{public static void main(String\[] args)

       {

        String s = "abcbade";

     int n1=s.indexOf('a');       //n1=0

     int n2=s.lastIndexOf('a');    //n2=4

        System.out.println("n1="+n1+",n2="+n2);

     int n3=s.indexOf('b',2);         //n3=3

     int n4=s.lastIndexOf('b',3);      //n3=3

        System.out.println("n3="+n3+",n4="+n4);

     int m1=s.indexOf("bc");        //m1=1

        int m2=s.lastIndexOf("ab");     //m2=4

        System.out.println("m1="+m1+",m2="+m2);

       }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

**12、valueOf：**

static [String]()

[valueOf]()(boolean b)  
          返回 boolean 参数的字符串表示形式。

static [String]()

[valueOf]()(char c)  
          返回 char 参数的字符串表示形式。

static [String]()

[valueOf]()(char\[] data)  
          返回 char 数组参数的字符串表示形式。

static [String]()

[valueOf]()(char\[] data, int offset, int count)  
        返回 char 数组参数的特定子数组的字符串表示形式。

static [String]()

[valueOf]()(double d)  
          返回 double 参数的字符串表示形式。

static [String]()

[valueOf]()(float f)  
          返回 float 参数的字符串表示形式。

static [String]()

[valueOf]()(int i)  
          返回 int 参数的字符串表示形式。

static [String]()

[valueOf]()(long l)  
          返回 long 参数的字符串表示形式。

static [String]()

[valueOf]()([Object]() obj)  
          返回 Object 参数的字符串表示形式。

例：

public class StringAPIDemo12

{public static void main(String\[] args)

       {

        char c\[]={'a','b','c','d','e','f'};

        int n=2011;

     String s1=String.valueOf(c);    //字符或字符数组均可转换

        String s2=String.valueOf(c,2,4);

        String s3=String.valueOf(n);   //只有单个整型可转换，整型数组不行

        System.out.println(s1);     //abcdef

        System.out.println(s2);     //cdef

        System.out.println(s3);     //2011

       }

}

 

 

 

 

 

 

 

**13、获取字符串长度length（）：**

int length()

例：

public class StringAPIDemo13

{public static void main(String\[] args)

       {

        String s="java";

        System.out.println(s.length());  //返回4

       }

}

 

**14、判断字符串是否为空：**

boolean isEmpty()     如果 length() 为 0，则返回 true；否则返回 false

例：

public class StringAPIDemo14

{public static void main(String\[] args)

       {

        String s1="";

        String s2="java";

        System.out.println(s1.isEmpty());    //返回true

        System.out.println(s2.isEmpty());    //返回false

       }

}

 

**15、去除字符串前后空格：**

String trim()  返回字符串的副本，忽略前导空白和尾部空白

例：

public class StringAPIDemo15

{public static void main(String\[] args)

       {

        String s1="   java  word   ";

        String s2="    ";

        String a="a";

        String b="b";

        System.out.println(s1.trim());        //返回“java  word”

        System.out.println(a+s2.trim()+b);   //返回“ab”，s2.trim()为空字符串””

       }

}

 

 

 

**16、返回字符串的子串**

String substring(int beginIndex) 返回一个新的字符串，它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始，直到此字符串末尾。 参数：beginIndex起始索引（包括）。

 

String substring(int beginIndex,int endIndex)  返回一个新字符串，它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始，直到索引 endIndex - 1 处的字符。因此，该子字符串的长度为 endIndex-beginIndex。 参数：beginIndex起始索引（包括）；endIndex结束索引（不包括）。

例：

public class StringAPIDemo16

{public static void main(String\[] args)

       {

        String s="java word";

        System.out.println(s.substring(1));   //返回“ava word”

        System.out.println(s.substring(1,6)); //返回“ava w”

       }

}

 

 

 

 

 

**17、替换字符串：**

String replace(char oldChar,char newChar)  返回一个新的字符串，它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的

String replace(char oldStr,char newStr)  返回一个新的字符串，它是通过用 newStr 替换此字符串中出现的所有 oldStr 得到的

例：

public class StringAPIDemo17

{public static void main(String\[] args)

       {

        String s="java";

        System.out.println(s.replace('a','A'));   //返回“jAvA”

        System.out.println(s.replace("ja","JA")); //返回“JAva”

       }

}

 

 

 

 

 

 

**18、拆分字符串：**

String\[ ] split(String regex) 根据给定正则表达式的匹配拆分此字符串

例：

public class StringAPIDemo18

{public static void main(String\[] args)

       {

        String s1="hellobbjavabword";

        String\[] s2=s1.split("b");

        System.out.println(s2.length);  //返回4

        for(int i=0;i&lt;s2.length;i++)

        System.out.println("s\["+i+"]="+s2\[i]);

        /\*s\[0]=hello ,s\[1]= ,s\[2]=java ,s\[3]=word,

        若split里的参数重复出现多次去掉一个，剩下的为空字符串

        如s1中出现bb，所以s2\[1]=""  \*/

        String a="a";

        String b="b";

        System.out.println(a+s2\[1]+b);//返回ab

       }

}