String详解, String和CharSequence区别, StringBuilder和StringBuffer的区别 (String系列之1)

本章主要介绍String和CharSequence的区别,以及它们的API详细使用方法。

转载请注明出处:http://www.cnblogs.com/skywang12345/p/string01.html

更多内容请参考:

1. StringBuilder 详解 (String系列之2)

2. StringBuffer 详解 (String系列之3)

String 简介

String 是java中的字符串,它继承于CharSequence。
String类所包含的API接口非常多。为了便于今后的使用,我对String的API进行了分类,并都给出的演示程序。

String 和 CharSequence 关系
String 继承于CharSequence,也就是说String也是CharSequence类型。
CharSequence是一个接口,它只包括length(), charAt(int index), subSequence(int start, int end)这几个API接口。除了String实现了CharSequence之外,StringBuffer和StringBuilder也实现了CharSequence接口。
需要说明的是,CharSequence就是字符序列,String, StringBuilder和StringBuffer本质上都是通过字符数组实现的!

 

StringBuilder 和 StringBuffer 的区别

StringBuilder 和 StringBuffer都是可变的字符序列。它们都继承于AbstractStringBuilder,实现了CharSequence接口。
但是,StringBuilder是非线程安全的,而StringBuffer是线程安全的

 

它们之间的关系图如下: 

 

更多关于“StringBuilder”的内容,请参考:http://www.cnblogs.com/skywang12345/p/string02.html

更多关于“StringBuffer”的内容,请参考  :http://www.cnblogs.com/skywang12345/p/string03.html

 

String 函数列表 

复制代码
public    String()
public    String(String original)
public    String(char[] value)
public    String(char[] value, int offset, int count)
public    String(byte[] bytes)
public    String(byte[] bytes, int offset, int length)
public    String(byte[] ascii, int hibyte)
public    String(byte[] ascii, int hibyte, int offset, int count)
public    String(byte[] bytes, String charsetName)
public    String(byte[] bytes, int offset, int length, String charsetName)
public    String(byte[] bytes, Charset charset)
public    String(byte[] bytes, int offset, int length, Charset charset)
public    String(int[] codePoints, int offset, int count)
public    String(StringBuffer buffer)
public    String(StringBuilder builder)

public char    charAt(int index)
public int    codePointAt(int index)
public int    codePointBefore(int index)
public int    codePointCount(int beginIndex, int endIndex)
public int    compareTo(String anotherString)
public int    compareToIgnoreCase(String str)
public String    concat(String str)
public boolean    contains(CharSequence s)
public boolean    contentEquals(StringBuffer sb)
public boolean    contentEquals(CharSequence cs)
public static String    copyValueOf(char[] data, int offset, int count)
public static String    copyValueOf(char[] data)
public boolean    endsWith(String suffix)
public boolean    equals(Object anObject)
public boolean    equalsIgnoreCase(String anotherString)
public static String    format(String format, Object[] args)
public static String    format(Locale l, String format, Object[] args)
public int    hashCode()
public int    indexOf(int ch)
public int    indexOf(int ch, int fromIndex)
public int    indexOf(String str)
public int    indexOf(String str, int fromIndex)
public String    intern()
public int    lastIndexOf(int ch)
public int    lastIndexOf(int ch, int fromIndex)
public int    lastIndexOf(String str)
public int    lastIndexOf(String str, int fromIndex)
public int    length()
public boolean    matches(String regex)
public int    offsetByCodePoints(int index, int codePointOffset)
public boolean    regionMatches(int toffset, String other, int ooffset, int len)
public boolean    regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
public String    replace(char oldChar, char newChar)
public String    replace(CharSequence target, CharSequence replacement)
public String    replaceAll(String regex, String replacement)
public String    replaceFirst(String regex, String replacement)
public String[]    split(String regex, int limit)
public String[]    split(String regex)
public boolean    startsWith(String prefix, int toffset)
public boolean    startsWith(String prefix)
public CharSequence    subSequence(int beginIndex, int endIndex)
public String    substring(int beginIndex)
public String    substring(int beginIndex, int endIndex)
public char[]    toCharArray()
public String    toLowerCase(Locale locale)
public String    toLowerCase()
public String    toString()
public String    toUpperCase(Locale locale)
public String    toUpperCase()
public String    trim()
public static String    valueOf(Object obj)
public static String    valueOf(char[] data)
public static String    valueOf(char[] data, int offset, int count)
public static String    valueOf(boolean b)
public static String    valueOf(char c)
public static String    valueOf(int i)
public static String    valueOf(long l)
public static String    valueOf(float f)
public static String    valueOf(double d)
public void    getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
public byte[]    getBytes(String charsetName)
public byte[]    getBytes(Charset charset)
public byte[]    getBytes()
public void    getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
public boolean    isEmpty()
复制代码

 

CharSequence和String源码

1. CharSequence源码(基于jdk1.7.40)

  View Code 

 

2. String.java源码(基于jdk1.7.40)

  View Code

说明:String的本质是字符序列,它是通过字符数组实现的!

 

演示程序

1. CharSequence

下面通过示例,演示CharSequence的使用方法!
源码如下(CharSequenceTest.java):

复制代码
 1 /**
 2  * CharSequence 演示程序
 3  *
 4  * @author skywang
 5  */
 6 import java.nio.charset.Charset;
 7 import java.io.UnsupportedEncodingException;
 8 
 9 public class CharSequenceTest {
10 
11     public static void main(String[] args) {
12         testCharSequence();
13     }
14 
15     /**
16      * CharSequence 测试程序
17      */
18     private static void testCharSequence() {
19         System.out.println("-------------------------------- testCharSequence -----------------------------");
20 
21         // 1. CharSequence的子类String
22         String str = "abcdefghijklmnopqrstuvwxyz";
23         System.out.println("1. String");
24         System.out.printf("   %-30s=%d\n", "str.length()", str.length());
25         System.out.printf("   %-30s=%c\n", "str.charAt(5)", str.charAt(5));
26         String substr = (String)str.subSequence(0,5);
27         System.out.printf("   %-30s=%s\n", "str.subSequence(0,5)", substr.toString());
28 
29         // 2. CharSequence的子类StringBuilder
30         StringBuilder strbuilder = new StringBuilder("abcdefghijklmnopqrstuvwxyz");
31         System.out.println("2. StringBuilder");
32         System.out.printf("   %-30s=%d\n", "strbuilder.length()", strbuilder.length());
33         System.out.printf("   %-30s=%c\n", "strbuilder.charAt(5)", strbuilder.charAt(5));
34         // 注意:StringBuilder的subSequence()返回的是,实际上是一个String对象!
35         String substrbuilder = (String)strbuilder.subSequence(0,5);
36         System.out.printf("   %-30s=%s\n", "strbuilder.subSequence(0,5)", substrbuilder.toString());
37 
38         // 3. CharSequence的子类StringBuffer
39         StringBuffer strbuffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
40         System.out.println("3. StringBuffer");
41         System.out.printf("   %-30s=%d\n", "strbuffer.length()", strbuffer.length());
42         System.out.printf("   %-30s=%c\n", "strbuffer.charAt(5)", strbuffer.charAt(5));
43         // 注意:StringBuffer的subSequence()返回的是,实际上是一个String对象!
44         String substrbuffer = (String)strbuffer.subSequence(0,5);
45         System.out.printf("   %-30s=%s\n", "strbuffer.subSequence(0,5)", substrbuffer.toString());
46 
47         System.out.println();
48     }
49 }
复制代码

运行结果

复制代码
-------------------------------- testCharSequence -----------------------------
1. String
   str.length()                  =26
   str.charAt(5)                 =f
   str.subSequence(0,5)          =abcde
2. StringBuilder
   strbuilder.length()           =26
   strbuilder.charAt(5)          =f
   strbuilder.subSequence(0,5)   =abcde
3. StringBuffer
   strbuffer.length()            =26
   strbuffer.charAt(5)           =f
   strbuffer.subSequence(0,5)    =abcde
复制代码

 

2. String 构造函数

下面通过示例,演示String的各种构造函数的使用方法!
源码如下(StringContructorTest.java):

复制代码
 1 /**
 2  * String 构造函数演示程序
 3  *
 4  * @author skywang
 5  */
 6 import java.nio.charset.Charset;
 7 import java.io.UnsupportedEncodingException;
 8 
 9 public class StringContructorTest {
10 
11     public static void main(String[] args) {
12         testStringConstructors() ;
13     }
14 
15     /**
16      * String 构造函数测试程序
17      */
18     private static void testStringConstructors() {
19         try {
20             System.out.println("-------------------------------- testStringConstructors -----------------------");
21 
22             String str01 = new String();
23             String str02 = new String("String02");
24             String str03 = new String(new char[]{'s','t','r','0','3'});
25             String str04 = new String(new char[]{'s','t','r','0','4'}, 1, 3);          // 1表示起始位置,3表示个数
26             String str05 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65});       // 0x61在ASC表中,对应字符"a"; 1表示起始位置,3表示长度
27             String str06 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65}, 1, 3); // 0x61在ASC表中,对应字符"a"; 1表示起始位置,3表示长度
28             String str07 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65}, 0);       // 0x61在ASC表中,对应字符"a";0,表示“高字节”
29             String str08 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65}, 0, 1, 3); // 0x61在ASC表中,对应字符"a"; 0,表示“高字节”;1表示起始位置,3表示长度
30             String str09 = new String(new byte[]{(byte)0xe5, (byte)0xad, (byte)0x97, /* 字-对应的utf-8编码 */ 
31                                                  (byte)0xe7, (byte)0xac, (byte)0xa6, /* 符-对应的utf-8编码 */ 
32                                                  (byte)0xe7, (byte)0xbc, (byte)0x96, /* 编-对应的utf-8编码 */ 
33                                                  (byte)0xe7, (byte)0xa0, (byte)0x81, /* 码-对应的utf-8编码 */ }, 
34                                       0, 12, "utf-8");  // 0表示起始位置,12表示长度。
35             String str10 = new String(new byte[]{(byte)0x5b, (byte)0x57, /* 字-对应的utf-16编码 */ 
36                                                  (byte)0x7b, (byte)0x26, /* 符-对应的utf-16编码 */ 
37                                                  (byte)0x7f, (byte)0x16, /* 编-对应的utf-16编码 */ 
38                                                  (byte)0x78, (byte)0x01, /* 码-对应的utf-16编码 */ }, 
39                                       0, 8, "utf-16");  // 0表示起始位置,8表示长度。
40             String str11 = new String(new byte[]{(byte)0xd7, (byte)0xd6, /* 字-对应的gb2312编码  */ 
41                                                  (byte)0xb7, (byte)0xfb, /* 符-对应的gb2312编码 */ 
42                                                  (byte)0xb1, (byte)0xe0, /* 编-对应的gb2312编码 */ 
43                                                  (byte)0xc2, (byte)0xeb, /* 码-对应的gb2312编码 */ }, 
44                                       Charset.forName("gb2312")); 
45             String str12 = new String(new byte[]{(byte)0xd7, (byte)0xd6, /* 字-对应的gbk编码 */ 
46                                                  (byte)0xb7, (byte)0xfb, /* 符-对应的gbk编码 */ 
47                                                  (byte)0xb1, (byte)0xe0, /* 编-对应的gbk编码 */ 
48                                                  (byte)0xc2, (byte)0xeb, /* 码-对应的gbk编码 */ }, 
49                                       0, 8, Charset.forName("gbk")); 
50             String str13 = new String(new int[] {0x5b57, 0x7b26, 0x7f16, 0x7801}, 0, 4);  // "字符编码"(\u5b57是‘字’的unicode编码)。0表示起始位置,4表示长度。
51             String str14 = new String(new StringBuffer("StringBuffer"));
52             String str15 = new String(new StringBuilder("StringBuilder"));
53 
54             System.out.printf(" str01=%s \n str02=%s \n str03=%s \n str04=%s \n str05=%s \n str06=%s \n str07=%s \n str08=%s\n str09=%s\n str10=%s\n str11=%s\n str12=%s\n str13=%s\n str14=%s\n str15=%s\n",
55                     str01, str02, str03, str04, str05, str06, str07, str08, str09, str10, str11, str12, str13, str14, str15);
56 
57 
58             System.out.println();
59         } catch (UnsupportedEncodingException e) {
60             e.printStackTrace();
61         }
62     }
63 }
复制代码

运行结果

复制代码
-------------------------------- testStringConstructors -----------------------
 str01= 
 str02=String02 
 str03=str03 
 str04=tr0 
 str05=abcde 
 str06=bcd 
 str07=abcde 
 str08=bcd
 str09=字符编码
 str10=字符编码
 str11=字符编码
 str12=字符编码
 str13=字符编码
 str14=StringBuffer
 str15=StringBuilder
复制代码

 

3. String 将各种对象转换成String的API

源码如下(StringValueTest.java):

复制代码
 1 /**
 2  * String value相关示例
 3  *
 4  * @author skywang
 5  */
 6 import java.util.HashMap;
 7 
 8 public class StringValueTest {
 9     
10     public static void main(String[] args) {
11         testValueAPIs() ;
12     }
13 
14     /**
15      * String 的valueOf()演示程序
16      */
17     private static void testValueAPIs() {
18         System.out.println("-------------------------------- testValueAPIs --------------------------------");
19         // 1. String    valueOf(Object obj)
20         //  实际上,返回的是obj.toString();
21         HashMap map = new HashMap();
22         map.put("1", "one");
23         map.put("2", "two");
24         map.put("3", "three");
25         System.out.printf("%-50s = %s\n", "String.valueOf(map)", String.valueOf(map));
26 
27         // 2.String    valueOf(boolean b)
28         System.out.printf("%-50s = %s\n", "String.valueOf(true)", String.valueOf(true));
29 
30         // 3.String    valueOf(char c)
31         System.out.printf("%-50s = %s\n", "String.valueOf('m')", String.valueOf('m'));
32 
33         // 4.String    valueOf(int i)
34         System.out.printf("%-50s = %s\n", "String.valueOf(96)", String.valueOf(96));
35 
36         // 5.String    valueOf(long l)
37         System.out.printf("%-50s = %s\n", "String.valueOf(12345L)", String.valueOf(12345L));
38 
39         // 6.String    valueOf(float f)
40         System.out.printf("%-50s = %s\n", "String.valueOf(1.414f)", String.valueOf(1.414f));
41 
42         // 7.String    valueOf(double d)
43         System.out.printf("%-50s = %s\n", "String.valueOf(3.14159d)", String.valueOf(3.14159d));
44 
45         // 8.String    valueOf(char[] data)
46         System.out.printf("%-50s = %s\n", "String.valueOf(new char[]{'s','k','y'})", String.valueOf(new char[]{'s','k','y'}));
47 
48         // 9.String    valueOf(char[] data, int offset, int count)
49         System.out.printf("%-50s = %s\n", "String.valueOf(new char[]{'s','k','y'}, 0, 2)", String.valueOf(new char[]{'s','k','y'}, 0, 2));
50 
51         System.out.println();
52     }
53 }
复制代码

运行结果

复制代码
-------------------------------- testValueAPIs --------------------------------
String.valueOf(map)                                = {3=three, 2=two, 1=one}
String.valueOf(true)                               = true
String.valueOf('m')                                = m
String.valueOf(96)                                 = 96
String.valueOf(12345L)                             = 12345
String.valueOf(1.414f)                             = 1.414
String.valueOf(3.14159d)                           = 3.14159
String.valueOf(new char[]{'s','k','y'})            = sky
String.valueOf(new char[]{'s','k','y'}, 0, 2)      = sk
复制代码

 

4. String 中index相关的API

源码如下(StringIndexTest.java):

复制代码
 1 /**
 2  * String 中index相关API演示
 3  *
 4  * @author skywang
 5  */
 6 
 7 public class StringIndexTest {
 8 
 9     public static void main(String[] args) {
10         testIndexAPIs() ;
11     }
12 
13     /**
14      * String 中index相关API演示
15      */
16     private static void testIndexAPIs() {
17         System.out.println("-------------------------------- testIndexAPIs --------------------------------");
18 
19         String istr = "abcAbcABCabCaBcAbCaBCabc";
20         System.out.printf("istr=%s\n", istr);
21 
22         // 1. 从前往后,找出‘a’第一次出现的位置
23         System.out.printf("%-30s = %d\n", "istr.indexOf((int)'a')", istr.indexOf((int)'a'));
24 
25         // 2. 从位置5开始,从前往后,找出‘a’第一次出现的位置
26         System.out.printf("%-30s = %d\n", "istr.indexOf((int)'a', 5)", istr.indexOf((int)'a', 5));
27 
28         // 3. 从后往前,找出‘a’第一次出现的位置
29         System.out.printf("%-30s = %d\n", "istr.lastIndexOf((int)'a')", istr.lastIndexOf((int)'a'));
30 
31         // 4. 从位置10开始,从后往前,找出‘a’第一次出现的位置
32         System.out.printf("%-30s = %d\n", "istr.lastIndexOf((int)'a', 10)", istr.lastIndexOf((int)'a', 10));
33 
34 
35         // 5. 从前往后,找出"bc"第一次出现的位置
36         System.out.printf("%-30s = %d\n", "istr.indexOf(\"bc\")", istr.indexOf("bc"));
37 
38         // 6. 从位置5开始,从前往后,找出"bc"第一次出现的位置
39         System.out.printf("%-30s = %d\n", "istr.indexOf(\"bc\", 5)", istr.indexOf("bc", 5));
40 
41         // 7. 从后往前,找出"bc"第一次出现的位置
42         System.out.printf("%-30s = %d\n", "istr.lastIndexOf(\"bc\")", istr.lastIndexOf("bc"));
43 
44         // 8. 从位置4开始,从后往前,找出"bc"第一次出现的位置
45         System.out.printf("%-30s = %d\n", "istr.lastIndexOf(\"bc\", 4)", istr.lastIndexOf("bc", 4));
46 
47         System.out.println();
48     }
49 }
复制代码

运行结果

复制代码
-------------------------------- testIndexAPIs --------------------------------
istr=abcAbcABCabCaBcAbCaBCabc
istr.indexOf((int)'a')         = 0
istr.indexOf((int)'a', 5)      = 9
istr.lastIndexOf((int)'a')     = 21
istr.lastIndexOf((int)'a', 10) = 9
istr.indexOf("bc")             = 1
istr.indexOf("bc", 5)          = 22
istr.lastIndexOf("bc")         = 22
istr.lastIndexOf("bc", 4)      = 4
复制代码

 

5. String “比较”操作的API

源码如下(StringCompareTest.java):

复制代码
 1 /**
 2  * String 中比较相关API演示
 3  *
 4  * @author skywang
 5  */
 6 
 7 public class StringCompareTest {
 8 
 9     public static void main(String[] args) {
10         testCompareAPIs() ;
11     }
12 
13     /**
14      * String 中比较相关API演示
15      */
16     private static void testCompareAPIs() {
17         System.out.println("-------------------------------- testCompareAPIs ------------------------------");
18 
19         //String str = "abcdefghijklmnopqrstuvwxyz";
20         String str = "abcAbcABCabCAbCabc";
21         System.out.printf("str=%s\n", str);
22 
23         // 1. 比较“2个String是否相等”
24         System.out.printf("%-50s = %b\n", 
25                 "str.equals(\"abcAbcABCabCAbCabc\")", 
26                 str.equals("abcAbcABCabCAbCabc"));
27 
28         // 2. 比较“2个String是否相等(忽略大小写)”
29         System.out.printf("%-50s = %b\n", 
30                 "str.equalsIgnoreCase(\"ABCABCABCABCABCABC\")", 
31                 str.equalsIgnoreCase("ABCABCABCABCABCABC"));
32 
33         // 3. 比较“2个String的大小”
34         System.out.printf("%-40s = %d\n", "str.compareTo(\"abce\")", str.compareTo("abce"));
35 
36         // 4. 比较“2个String的大小(忽略大小写)”
37         System.out.printf("%-40s = %d\n", "str.compareToIgnoreCase(\"ABC\")", str.compareToIgnoreCase("ABC"));
38 
39         // 5. 字符串的开头是不是"ab"
40         System.out.printf("%-40s = %b\n", "str.startsWith(\"ab\")", str.startsWith("ab"));
41 
42         // 6. 字符串的从位置3开头是不是"ab"
43         System.out.printf("%-40s = %b\n", "str.startsWith(\"Ab\")", str.startsWith("Ab", 3));
44 
45         // 7. 字符串的结尾是不是"bc"
46         System.out.printf("%-40s = %b\n", "str.endsWith(\"bc\")", str.endsWith("bc"));
47 
48         // 8. 字符串的是不是包含"ABC"
49         System.out.printf("%-40s = %b\n", "str.contains(\"ABC\")", str.contains("ABC"));
50 
51         // 9. 比较2个字符串的部分内容
52         String region1 = str.substring(2, str.length());    // 获取str位置3(包括)到末尾(不包括)的子字符串
53         // 将“str中从位置2开始的字符串”和“region1中位置0开始的字符串”进行比较,比较长度是5。
54         System.out.printf("regionMatches(%s) = %b\n", region1, 
55                 str.regionMatches(2, region1, 0, 5));
56 
57         // 10. 比较2个字符串的部分内容(忽略大小写)
58         String region2 = region1.toUpperCase();    // 将region1转换为大写
59         String region3 = region1.toLowerCase();    // 将region1转换为小写
60         System.out.printf("regionMatches(%s) = %b\n", region2, 
61                 str.regionMatches(2, region2, 0, 5));
62         System.out.printf("regionMatches(%s) = %b\n", region3, 
63                 str.regionMatches(2, region3, 0, 5));
64 
65         // 11. 比较“String”和“StringBuffer”的内容是否相等
66         System.out.printf("%-60s = %b\n", 
67                 "str.contentEquals(new StringBuffer(\"abcAbcABCabCAbCabc\"))", 
68                 str.contentEquals(new StringBuffer("abcAbcABCabCAbCabc")));
69 
70         // 12. 比较“String”和“StringBuilder”的内容是否相等
71         System.out.printf("%-60s = %b\n", 
72                 "str.contentEquals(new StringBuilder(\"abcAbcABCabCAbCabc\"))", 
73                 str.contentEquals(new StringBuilder("abcAbcABCabCAbCabc")));
74 
75         // 13. match()测试程序
76         // 正则表达式 xxx.xxx.xxx.xxx,其中xxx中x的取值可以是0~9,xxx中有1~3位。
77         String reg_ipv4 = "[0-9]{3}(\\.[0-9]{1,3}){3}";    
78 
79         String ipv4addr1 = "192.168.1.102";
80         String ipv4addr2 = "192.168";
81         System.out.printf("%-40s = %b\n", "ipv4addr1.matches()", ipv4addr1.matches(reg_ipv4));
82         System.out.printf("%-40s = %b\n", "ipv4addr2.matches()", ipv4addr2.matches(reg_ipv4));
83 
84         System.out.println();
85     }
86 }
复制代码

运行结果

复制代码
-------------------------------- testCompareAPIs ------------------------------
str=abcAbcABCabCAbCabc
str.equals("abcAbcABCabCAbCabc")                   = true
str.equalsIgnoreCase("ABCABCABCABCABCABC")         = true
str.compareTo("abce")                    = -36
str.compareToIgnoreCase("ABC")           = 15
str.startsWith("ab")                     = true
str.startsWith("Ab")                     = true
str.endsWith("bc")                       = true
str.contains("ABC")                      = true
regionMatches(cAbcABCabCAbCabc) = true
regionMatches(CABCABCABCABCABC) = false
regionMatches(cabcabcabcabcabc) = false
str.contentEquals(new StringBuffer("abcAbcABCabCAbCabc"))    = true
str.contentEquals(new StringBuilder("abcAbcABCabCAbCabc"))   = true
ipv4addr1.matches()                      = true
ipv4addr2.matches()                      = false
复制代码

 

6. String “修改(追加/替换/截取/分割)”操作的API

源码如下(StringModifyTest.java):

复制代码
 1 /**
 2  * String 中 修改(追加/替换/截取/分割)字符串的相关API演示
 3  *
 4  * @author skywang
 5  */
 6 
 7 public class StringModifyTest {
 8     
 9     public static void main(String[] args) {
10         testModifyAPIs() ;
11     }
12 
13     /**
14      * String 中 修改(追加/替换/截取/分割)字符串的相关API演示
15      */
16     private static void testModifyAPIs() {
17         System.out.println("-------------------------------- testModifyAPIs -------------------------------");
18 
19         String str = " abcAbcABCabCAbCabc ";
20         System.out.printf("str=%s, len=%d\n", str, str.length());
21 
22         // 1.追加
23         // 将"123"追加到str之后
24         System.out.printf("%-30s = %s\n", "str.concat(\"123\")", 
25                 str.concat("123"));
26 
27         // 2.截取
28         // 截取str中从位置7(包括)开始的元素。
29         System.out.printf("%-30s = %s\n", "str.substring(7)", str.substring(7));
30         // 截取str中从位置7(包括)到位置10(不包括)之间的元素。
31         System.out.printf("%-30s = %s\n", "str.substring(7, 10)", str.substring(7, 10));
32         // 删除str中首位的空格,并返回。
33         System.out.printf("%-30s = %s, len=%d\n", "str.trim()", str.trim(), str.trim().length());
34 
35         // 3.替换
36         // 将str中的 “字符‘a’” 全部替换为 “字符‘_’”
37         System.out.printf("%-30s = %s\n", "str.replace('a', 'M')", str.replace('a', '_'));
38         // 将str中的第一次出现的“字符串“a”” 替换为 “字符串“###””
39         System.out.printf("%-30s = %s\n", "str.replaceFirst(\"a\", \"###\")", str.replaceFirst("a", "###"));
40         // 将str中的 “字符串“a”” 全部替换为 “字符串“$$$””
41         System.out.printf("%-30s = %s\n", "str.replace(\"a\", \"$$$\")", str.replace("a", "$$$"));
42 
43         // 4.分割
44         // 以“b”作为分隔符,对str进行分割
45         String[] splits = str.split("b");
46         for (int i=0; i<splits.length; i++) {
47             System.out.printf("splits[%d]=%s\n", i, splits[i]);
48         }
49 
50         System.out.println();
51     }
52 }
复制代码

运行结果

复制代码
-------------------------------- testModifyAPIs -------------------------------
str= abcAbcABCabCAbCabc , len=20
str.concat("123")              =  abcAbcABCabCAbCabc 123
str.substring(7)               = ABCabCAbCabc 
str.substring(7, 10)           = ABC
str.trim()                     = abcAbcABCabCAbCabc, len=18
str.replace('a', 'M')          =  _bcAbcABC_bCAbC_bc 
str.replaceFirst("a", "###")   =  ###bcAbcABCabCAbCabc 
str.replace("a", "$$$")        =  $$$bcAbcABC$$$bCAbC$$$bc 
splits[0]= a
splits[1]=cA
splits[2]=cABCa
splits[3]=CA
splits[4]=Ca
splits[5]=c 
复制代码

 

7. String 操作Unicode的API

源码如下(StringUnicodeTest.java):

复制代码
 1 /**
 2  * String 中与unicode相关的API
 3  *
 4  * @author skywang
 5  */
 6 
 7 public class StringUnicodeTest {
 8     
 9     public static void main(String[] args) {
10         testUnicodeAPIs() ;
11     }
12 
13     /**
14      * String 中与unicode相关的API
15      */
16     private static void testUnicodeAPIs() {
17         System.out.println("-------------------------------- testUnicodeAPIs ------------------------------");
18 
19         String ustr = new String(new int[] {0x5b57, 0x7b26, 0x7f16, 0x7801}, 0, 4);  // "字符编码"(\u5b57是‘字’的unicode编码)。0表示起始位置,4表示长度。
20         System.out.printf("ustr=%s\n", ustr);
21 
22         //  获取位置0的元素对应的unciode编码
23         System.out.printf("%-30s = 0x%x\n", "ustr.codePointAt(0)", ustr.codePointAt(0));
24 
25         // 获取位置2之前的元素对应的unciode编码
26         System.out.printf("%-30s = 0x%x\n", "ustr.codePointBefore(2)", ustr.codePointBefore(2));
27 
28         // 获取位置1开始偏移2个代码点的索引
29         System.out.printf("%-30s = %d\n", "ustr.offsetByCodePoints(1, 2)", ustr.offsetByCodePoints(1, 2));
30 
31         // 获取第0~3个元素之间的unciode编码的个数
32         System.out.printf("%-30s = %d\n", "ustr.codePointCount(0, 3)", ustr.codePointCount(0, 3));
33 
34         System.out.println();
35     }
36 }
复制代码

运行结果

-------------------------------- testUnicodeAPIs ------------------------------
ustr=字符编码
ustr.codePointAt(0)            = 0x5b57
ustr.codePointBefore(2)        = 0x7b26
ustr.offsetByCodePoints(1, 2)  = 3
ustr.codePointCount(0, 3)      = 3

 

8. String 剩余的API

源码如下(StringOtherTest.java):

复制代码
 1 /**
 2  * String 中其它的API
 3  *
 4  * @author skywang
 5  */
 6 
 7 public class StringOtherTest {
 8     
 9     public static void main(String[] args) {
10         testOtherAPIs() ;
11     }
12 
13     /**
14      * String 中其它的API
15      */
16     private static void testOtherAPIs() {
17         System.out.println("-------------------------------- testOtherAPIs --------------------------------");
18 
19         String str = "0123456789";
20         System.out.printf("str=%s\n", str);
21 
22         // 1. 字符串长度
23         System.out.printf("%s = %d\n", "str.length()", str.length());
24 
25         // 2. 字符串是否为空
26         System.out.printf("%s = %b\n", "str.isEmpty()", str.isEmpty());
27 
28         // 3. [字节] 获取字符串对应的字节数组
29         byte[] barr = str.getBytes();
30         for (int i=0; i<barr.length; i++) {
31                System.out.printf("barr[%d]=0x%x ", i, barr[i]);
32         }
33         System.out.println();
34 
35         // 4. [字符] 获取字符串位置4的字符
36         System.out.printf("%s = %c\n", "str.charAt(4)", str.charAt(4));
37 
38         // 5. [字符] 获取字符串对应的字符数组
39         char[] carr = str.toCharArray();
40         for (int i=0; i<carr.length; i++) {
41                System.out.printf("carr[%d]=%c ", i, carr[i]);
42         }
43         System.out.println();
44 
45         // 6. [字符] 获取字符串中部分元素对应的字符数组
46         char[] carr2 = new char[3];
47         str.getChars(6, 9, carr2, 0);
48         for (int i=0; i<carr2.length; i++) {
49                System.out.printf("carr2[%d]=%c ", i, carr2[i]);
50         }
51         System.out.println();
52 
53         // 7. [字符] 获取字符数组对应的字符串
54         System.out.printf("%s = %s\n", 
55                 "str.copyValueOf(new char[]{'a','b','c','d','e'})", 
56                 String.copyValueOf(new char[]{'a','b','c','d','e'}));
57 
58         // 8. [字符] 获取字符数组中部分元素对应的字符串
59         System.out.printf("%s = %s\n", 
60                 "str.copyValueOf(new char[]{'a','b','c','d','e'}, 1, 4)", 
61                 String.copyValueOf(new char[]{'a','b','c','d','e'}, 1, 4));
62 
63         // 9. format()示例,将对象数组按指定格式转换为字符串
64         System.out.printf("%s = %s\n", 
65                 "str.format()", 
66                 String.format("%s-%d-%b", "abc", 3, true));
67 
68         System.out.println();
69     }
70 }
复制代码

运行结果

复制代码
-------------------------------- testOtherAPIs --------------------------------
str=0123456789
str.length() = 10
str.isEmpty() = false
barr[0]=0x30 barr[1]=0x31 barr[2]=0x32 barr[3]=0x33 barr[4]=0x34 barr[5]=0x35 barr[6]=0x36 barr[7]=0x37 barr[8]=0x38 barr[9]=0x39 
str.charAt(4) = 4
carr[0]=0 carr[1]=1 carr[2]=2 carr[3]=3 carr[4]=4 carr[5]=5 carr[6]=6 carr[7]=7 carr[8]=8 carr[9]=9 
carr2[0]=6 carr2[1]=7 carr2[2]=8 
str.copyValueOf(new char[]{'a','b','c','d','e'}) = abcde
str.copyValueOf(new char[]{'a','b','c','d','e'}, 1, 4) = bcde
str.format() = abc-3-true
复制代码

 

9. String 完整示例

下面的示例是整合上面的几个示例的完整的String演示程序,源码如下(StringAPITest.java):

复制代码
  1 /**
  2  * String 演示程序
  3  *
  4  * @author skywang
  5  */
  6 import java.util.HashMap;
  7 import java.nio.charset.Charset;
  8 import java.io.UnsupportedEncodingException;
  9 
 10 public class StringAPITest {
 11     
 12     public static void main(String[] args) {
 13         testStringConstructors() ; // String 构造函数测试程序
 14         testValueAPIs() ;          // String 的valueOf()演示程序
 15         testIndexAPIs() ;          // String 中index相关API演示
 16         testCompareAPIs() ;        // String 中比较相关API演示
 17         testModifyAPIs() ;         // String 中 修改(追加/替换/截取/分割)字符串的相关API演示
 18         testUnicodeAPIs() ;        // String 中与unicode相关的API
 19         testOtherAPIs() ;          // String 中其它的API
 20     }
 21 
 22     /**
 23      * String 构造函数测试程序
 24      */
 25     private static void testStringConstructors() {
 26         try {
 27             System.out.println("-------------------------------- testStringConstructors -----------------------");
 28 
 29             String str01 = new String();
 30             String str02 = new String("String02");
 31             String str03 = new String(new char[]{'s','t','r','0','3'});
 32             String str04 = new String(new char[]{'s','t','r','0','4'}, 1, 3);          // 1表示起始位置,3表示个数
 33             String str05 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65});       // 0x61在ASC表中,对应字符"a"; 1表示起始位置,3表示长度
 34             String str06 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65}, 1, 3); // 0x61在ASC表中,对应字符"a"; 1表示起始位置,3表示长度
 35             String str07 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65}, 0);       // 0x61在ASC表中,对应字符"a";0,表示“高字节”
 36             String str08 = new String(new byte[]{0x61, 0x62, 0x63, 0x64, 0x65}, 0, 1, 3); // 0x61在ASC表中,对应字符"a"; 0,表示“高字节”;1表示起始位置,3表示长度
 37             String str09 = new String(new byte[]{(byte)0xe5, (byte)0xad, (byte)0x97, /* 字-对应的utf-8编码 */ 
 38                                                  (byte)0xe7, (byte)0xac, (byte)0xa6, /* 符-对应的utf-8编码 */ 
 39                                                  (byte)0xe7, (byte)0xbc, (byte)0x96, /* 编-对应的utf-8编码 */ 
 40                                                  (byte)0xe7, (byte)0xa0, (byte)0x81, /* 码-对应的utf-8编码 */ }, 
 41                                       0, 12, "utf-8");  // 0表示起始位置,12表示长度。
 42             String str10 = new String(new byte[]{(byte)0x5b, (byte)0x57, /* 字-对应的utf-16编码 */ 
 43                                                  (byte)0x7b, (byte)0x26, /* 符-对应的utf-16编码 */ 
 44                                                  (byte)0x7f, (byte)0x16, /* 编-对应的utf-16编码 */ 
 45                                                  (byte)0x78, (byte)0x01, /* 码-对应的utf-16编码 */ }, 
 46                                       0, 8, "utf-16");  // 0表示起始位置,8表示长度。
 47             String str11 = new String(new byte[]{(byte)0xd7, (byte)0xd6, /* 字-对应的gb2312编码  */ 
 48                                                  (byte)0xb7, (byte)0xfb, /* 符-对应的gb2312编码 */ 
 49                                                  (byte)0xb1, (byte)0xe0, /* 编-对应的gb2312编码 */ 
 50                                                  (byte)0xc2, (byte)0xeb, /* 码-对应的gb2312编码 */ }, 
 51                                       Charset.forName("gb2312")); 
 52             String str12 = new String(new byte[]{(byte)0xd7, (byte)0xd6, /* 字-对应的gbk编码 */ 
 53                                                  (byte)0xb7, (byte)0xfb, /* 符-对应的gbk编码 */ 
 54                                                  (byte)0xb1, (byte)0xe0, /* 编-对应的gbk编码 */ 
 55                                                  (byte)0xc2, (byte)0xeb, /* 码-对应的gbk编码 */ }, 
 56                                       0, 8, Charset.forName("gbk")); 
 57             String str13 = new String(new int[] {0x5b57, 0x7b26, 0x7f16, 0x7801}, 0, 4);  // "字符编码"(\u5b57是‘字’的unicode编码)。0表示起始位置,4表示长度。
 58             String str14 = new String(new StringBuffer("StringBuffer"));
 59             String str15 = new String(new StringBuilder("StringBuilder"));
 60 
 61             System.out.printf(" str01=%s \n str02=%s \n str03=%s \n str04=%s \n str05=%s \n str06=%s \n str07=%s \n str08=%s\n str09=%s\n str10=%s\n str11=%s\n str12=%s\n str13=%s\n str14=%s\n str15=%s\n",
 62                     str01, str02, str03, str04, str05, str06, str07, str08, str09, str10, str11, str12, str13, str14, str15);
 63 
 64 
 65             System.out.println();
 66         } catch (UnsupportedEncodingException e) {
 67             e.printStackTrace();
 68         }
 69     }
 70 
 71     /**
 72      * String 中其它的API
 73      */
 74     private static void testOtherAPIs() {
 75         System.out.println("-------------------------------- testOtherAPIs --------------------------------");
 76 
 77         String str = "0123456789";
 78         System.out.printf("str=%s\n", str);
 79 
 80         // 1. 字符串长度
 81         System.out.printf("%s = %d\n", "str.length()", str.length());
 82 
 83         // 2. 字符串是否为空
 84         System.out.printf("%s = %b\n", "str.isEmpty()", str.isEmpty());
 85 
 86         // 3. [字节] 获取字符串对应的字节数组
 87         byte[] barr = str.getBytes();
 88         for (int i=0; i<barr.length; i++) {
 89                System.out.printf("barr[%d]=0x%x ", i, barr[i]);
 90         }
 91         System.out.println();
 92 
 93         // 4. [字符] 获取字符串位置4的字符
 94         System.out.printf("%s = %c\n", "str.charAt(4)", str.charAt(4));
 95 
 96         // 5. [字符] 获取字符串对应的字符数组
 97         char[] carr = str.toCharArray();
 98         for (int i=0; i<carr.length; i++) {
 99                System.out.printf("carr[%d]=%c ", i, carr[i]);
100         }
101         System.out.println();
102 
103         // 6. [字符] 获取字符串中部分元素对应的字符数组
104         char[] carr2 = new char[3];
105         str.getChars(6, 9, carr2, 0);
106         for (int i=0; i<carr2.length; i++) {
107                System.out.printf("carr2[%d]=%c ", i, carr2[i]);
108         }
109         System.out.println();
110 
111         // 7. [字符] 获取字符数组对应的字符串
112         System.out.printf("%s = %s\n", 
113                 "str.copyValueOf(new char[]{'a','b','c','d','e'})", 
114                 String.copyValueOf(new char[]{'a','b','c','d','e'}));
115 
116         // 8. [字符] 获取字符数组中部分元素对应的字符串
117         System.out.printf("%s = %s\n", 
118                 "str.copyValueOf(new char[]{'a','b','c','d','e'}, 1, 4)", 
119                 String.copyValueOf(new char[]{'a','b','c','d','e'}, 1, 4));
120 
121         // 9. format()示例,将对象数组按指定格式转换为字符串
122         System.out.printf("%s = %s\n", 
123                 "str.format()", 
124                 String.format("%s-%d-%b", "abc", 3, true));
125 
126         System.out.println();
127     }
128 
129     /**
130      * String 中 修改(追加/替换/截取/分割)字符串的相关API演示
131      */
132     private static void testModifyAPIs() {
133         System.out.println("-------------------------------- testModifyAPIs -------------------------------");
134 
135         String str = " abcAbcABCabCAbCabc ";
136         System.out.printf("%s, len=%d\n", str, str.length());
137 
138         // 1.追加
139         // 将"123"追加到str之后
140         System.out.printf("%-30s = %s\n", "str.concat(\"123\")", 
141                 str.concat("123"));
142 
143         // 2.截取
144         // 截取str中从位置7(包括)开始的元素。
145         System.out.printf("%-30s = %s\n", "str.substring(7)", str.substring(7));
146         // 截取str中从位置7(包括)到位置10(不包括)之间的元素。
147         System.out.printf("%-30s = %s\n", "str.substring(7, 10)", str.substring(7, 10));
148         // 删除str中首位的空格,并返回。
149         System.out.printf("%-30s = %s, len=%d\n", "str.trim()", str.trim(), str.trim().length());
150 
151         // 3.替换
152         // 将str中的 “字符‘a’” 全部替换为 “字符‘_’”
153         System.out.printf("%-30s = %s\n", "str.replace('a', 'M')", str.replace('a', '_'));
154         // 将str中的第一次出现的“字符串“a”” 替换为 “字符串“###””
155         System.out.printf("%-30s = %s\n", "str.replaceFirst(\"a\", \"###\")", str.replaceFirst("a", "###"));
156         // 将str中的 “字符串“a”” 全部替换为 “字符串“$$$””
157         System.out.printf("%-30s = %s\n", "str.replace(\"a\", \"$$$\")", str.replace("a", "$$$"));
158 
159         // 4.分割
160         // 以“b”作为分隔符,对str进行分割
161         String[] splits = str.split("b");
162         for (int i=0; i<splits.length; i++) {
163             System.out.printf("splits[%d]=%s\n", i, splits[i]);
164         }
165 
166         System.out.println();
167     }
168 
169 
170     /**
171      * String 中比较相关API演示
172      */
173     private static void testCompareAPIs() {
174         System.out.println("-------------------------------- testCompareAPIs ------------------------------");
175 
176         //String str = "abcdefghijklmnopqrstuvwxyz";
177         String str = "abcAbcABCabCAbCabc";
178         System.out.printf("%s\n", str);
179 
180         // 1. 比较“2个String是否相等”
181         System.out.printf("%-50s = %b\n", 
182                 "str.equals(\"abcAbcABCabCAbCabc\")", 
183                 str.equals("abcAbcABCabCAbCabc"));
184 
185         // 2. 比较“2个String是否相等(忽略大小写)”
186         System.out.printf("%-50s = %b\n", 
187                 "str.equalsIgnoreCase(\"ABCABCABCABCABCABC\")", 
188                 str.equalsIgnoreCase("ABCABCABCABCABCABC"));
189 
190         // 3. 比较“2个String的大小”
191         System.out.printf("%-40s = %d\n", "str.compareTo(\"abce\")", str.compareTo("abce"));
192 
193         // 4. 比较“2个String的大小(忽略大小写)”
194         System.out.printf("%-40s = %d\n", "str.compareToIgnoreCase(\"ABC\")", str.compareToIgnoreCase("ABC"));
195 
196         // 5. 字符串的开头是不是"ab"
197         System.out.printf("%-40s = %b\n", "str.startsWith(\"ab\")", str.startsWith("ab"));
198 
199         // 6. 字符串的从位置3开头是不是"ab"
200         System.out.printf("%-40s = %b\n", "str.startsWith(\"Ab\")", str.startsWith("Ab", 3));
201 
202         // 7. 字符串的结尾是不是"bc"
203         System.out.printf("%-40s = %b\n", "str.endsWith(\"bc\")", str.endsWith("bc"));
204 
205         // 8. 字符串的是不是包含"ABC"
206         System.out.printf("%-40s = %b\n", "str.contains(\"ABC\")", str.contains("ABC"));
207 
208         // 9. 比较2个字符串的部分内容
209         String region1 = str.substring(2, str.length());    // 获取str位置3(包括)到末尾(不包括)的子字符串
210         // 将“str中从位置2开始的字符串”和“region1中位置0开始的字符串”进行比较,比较长度是5。
211         System.out.printf("regionMatches(%s) = %b\n", region1, 
212                 str.regionMatches(2, region1, 0, 5));
213 
214         // 10. 比较2个字符串的部分内容(忽略大小写)
215         String region2 = region1.toUpperCase();    // 将region1转换为大写
216         String region3 = region1.toLowerCase();    // 将region1转换为小写
217         System.out.printf("regionMatches(%s) = %b\n", region2, 
218                 str.regionMatches(2, region2, 0, 5));
219         System.out.printf("regionMatches(%s) = %b\n", region3, 
220                 str.regionMatches(2, region3, 0, 5));
221 
222         // 11. 比较“String”和“StringBuffer”的内容是否相等
223         System.out.printf("%-60s = %b\n", 
224                 "str.contentEquals(new StringBuffer(\"abcAbcABCabCAbCabc\"))", 
225                 str.contentEquals(new StringBuffer("abcAbcABCabCAbCabc")));
226 
227         // 12. 比较“String”和“StringBuilder”的内容是否相等
228         System.out.printf("%-60s = %b\n", 
229                 "str.contentEquals(new StringBuilder(\"abcAbcABCabCAbCabc\"))", 
230                 str.contentEquals(new StringBuilder("abcAbcABCabCAbCabc")));
231 
232         // 13. match()测试程序
233         // 正则表达式 xxx.xxx.xxx.xxx,其中xxx中x的取值可以是0~9,xxx中有1~3位。
234         String reg_ipv4 = "[0-9]{3}(\\.[0-9]{1,3}){3}";    
235 
236         String ipv4addr1 = "192.168.1.102";
237         String ipv4addr2 = "192.168";
238         System.out.printf("%-40s = %b\n", "ipv4addr1.matches()", ipv4addr1.matches(reg_ipv4));
239         System.out.printf("%-40s = %b\n", "ipv4addr2.matches()", ipv4addr2.matches(reg_ipv4));
240 
241         System.out.println();
242     }
243 
244     /**
245      * String 的valueOf()演示程序
246      */
247     private static void testValueAPIs() {
248         System.out.println("-------------------------------- testValueAPIs --------------------------------");
249         // 1. String    valueOf(Object obj)
250         //  实际上,返回的是obj.toString();
251         HashMap map = new HashMap();
252         map.put("1", "one");
253         map.put("2", "two");
254         map.put("3", "three");
255         System.out.printf("%-50s = %s\n", "String.valueOf(map)", String.valueOf(map));
256 
257         // 2.String    valueOf(boolean b)
258         System.out.printf("%-50s = %s\n", "String.valueOf(true)", String.valueOf(true));
259 
260         // 3.String    valueOf(char c)
261         System.out.printf("%-50s = %s\n", "String.valueOf('m')", String.valueOf('m'));
262 
263         // 4.String    valueOf(int i)
264         System.out.printf("%-50s = %s\n", "String.valueOf(96)", String.valueOf(96));
265 
266         // 5.String    valueOf(long l)
267         System.out.printf("%-50s = %s\n", "String.valueOf(12345L)", String.valueOf(12345L));
268 
269         // 6.String    valueOf(float f)
270         System.out.printf("%-50s = %s\n", "String.valueOf(1.414f)", String.valueOf(1.414f));
271 
272         // 7.String    valueOf(double d)
273         System.out.printf("%-50s = %s\n", "String.valueOf(3.14159d)", String.valueOf(3.14159d));
274 
275         // 8.String    valueOf(char[] data)
276         System.out.printf("%-50s = %s\n", "String.valueOf(new char[]{'s','k','y'})", String.valueOf(new char[]{'s','k','y'}));
277 
278         // 9.String    valueOf(char[] data, int offset, int count)
279         System.out.printf("%-50s = %s\n", "String.valueOf(new char[]{'s','k','y'}, 0, 2)", String.valueOf(new char[]{'s','k','y'}, 0, 2));
280 
281         System.out.println();
282     }
283 
284     /**
285      * String 中index相关API演示
286      */
287     private static void testIndexAPIs() {
288         System.out.println("-------------------------------- testIndexAPIs --------------------------------");
289 
290         String istr = "abcAbcABCabCaBcAbCaBCabc";
291         System.out.printf("istr=%s\n", istr);
292 
293         // 1. 从前往后,找出‘a’第一次出现的位置
294         System.out.printf("%-30s = %d\n", "istr.indexOf((int)'a')", istr.indexOf((int)'a'));
295 
296         // 2. 从位置5开始,从前往后,找出‘a’第一次出现的位置
297         System.out.printf("%-30s = %d\n", "istr.indexOf((int)'a', 5)", istr.indexOf((int)'a', 5));
298 
299         // 3. 从后往前,找出‘a’第一次出现的位置
300         System.out.printf("%-30s = %d\n", "istr.lastIndexOf((int)'a')", istr.lastIndexOf((int)'a'));
301 
302         // 4. 从位置10开始,从后往前,找出‘a’第一次出现的位置
303         System.out.printf("%-30s = %d\n", "istr.lastIndexOf((int)'a', 10)", istr.lastIndexOf((int)'a', 10));
304 
305 
306         // 5. 从前往后,找出"bc"第一次出现的位置
307         System.out.printf("%-30s = %d\n", "istr.indexOf(\"bc\")", istr.indexOf("bc"));
308 
309         // 6. 从位置5开始,从前往后,找出"bc"第一次出现的位置
310         System.out.printf("%-30s = %d\n", "istr.indexOf(\"bc\", 5)", istr.indexOf("bc", 5));
311 
312         // 7. 从后往前,找出"bc"第一次出现的位置
313         System.out.printf("%-30s = %d\n", "istr.lastIndexOf(\"bc\")", istr.lastIndexOf("bc"));
314 
315         // 8. 从位置4开始,从后往前,找出"bc"第一次出现的位置
316         System.out.printf("%-30s = %d\n", "istr.lastIndexOf(\"bc\", 4)", istr.lastIndexOf("bc", 4));
317 
318         System.out.println();
319     }
320 
321     /**
322      * String 中与unicode相关的API
323      */
324     private static void testUnicodeAPIs() {
325         System.out.println("-------------------------------- testUnicodeAPIs ------------------------------");
326 
327         String ustr = new String(new int[] {0x5b57, 0x7b26, 0x7f16, 0x7801}, 0, 4);  // "字符编码"(\u5b57是‘字’的unicode编码)。0表示起始位置,4表示长度。
328         System.out.printf("ustr=%s\n", ustr);
329 
330         //  获取位置0的元素对应的unciode编码
331         System.out.printf("%-30s = 0x%x\n", "ustr.codePointAt(0)", ustr.codePointAt(0));
332 
333         // 获取位置2之前的元素对应的unciode编码
334         System.out.printf("%-30s = 0x%x\n", "ustr.codePointBefore(2)", ustr.codePointBefore(2));
335 
336         // 获取位置1开始的元素对应的unciode编码
337         System.out.printf("%-30s = %d\n", "ustr.offsetByCodePoints(1, 2)", ustr.offsetByCodePoints(1, 2));
338 
339         // 获取第0~3个元素之间的unciode编码的个数
340         System.out.printf("%-30s = %d\n", "ustr.codePointCount(0, 3)", ustr.codePointCount(0, 3));
341 
342         System.out.println();
343     }
344 }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值