skywang12345

导航

 

本章主要介绍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)

 1 package java.lang;
 2 
 3 public interface CharSequence {
 4 
 5     int length();
 6 
 7     char charAt(int index);
 8 
 9     CharSequence subSequence(int start, int end);
10 
11     public String toString();
12 }
View Code

 

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

   1 package java.lang;
   2 
   3 import java.io.ObjectStreamField;
   4 import java.io.UnsupportedEncodingException;
   5 import java.nio.charset.Charset;
   6 import java.util.ArrayList;
   7 import java.util.Arrays;
   8 import java.util.Comparator;
   9 import java.util.Formatter;
  10 import java.util.Locale;
  11 import java.util.regex.Matcher;
  12 import java.util.regex.Pattern;
  13 import java.util.regex.PatternSyntaxException;
  14 
  15 public final class String
  16     implements java.io.Serializable, Comparable<String>, CharSequence {
  17     private final char value[];
  18 
  19     private int hash;
  20 
  21     private static final long serialVersionUID = -6849794470754667710L;
  22 
  23     private static final ObjectStreamField[] serialPersistentFields =
  24             new ObjectStreamField[0];
  25 
  26     public String() {
  27         this.value = new char[0];
  28     }
  29 
  30     public String(String original) {
  31         this.value = original.value;
  32         this.hash = original.hash;
  33     }
  34 
  35     public String(char value[]) {
  36         this.value = Arrays.copyOf(value, value.length);
  37     }
  38 
  39     public String(char value[], int offset, int count) {
  40         if (offset < 0) {
  41             throw new StringIndexOutOfBoundsException(offset);
  42         }
  43         if (count < 0) {
  44             throw new StringIndexOutOfBoundsException(count);
  45         }
  46         // Note: offset or count might be near -1>>>1.
  47         if (offset > value.length - count) {
  48             throw new StringIndexOutOfBoundsException(offset + count);
  49         }
  50         this.value = Arrays.copyOfRange(value, offset, offset+count);
  51     }
  52 
  53     public String(int[] codePoints, int offset, int count) {
  54         if (offset < 0) {
  55             throw new StringIndexOutOfBoundsException(offset);
  56         }
  57         if (count < 0) {
  58             throw new StringIndexOutOfBoundsException(count);
  59         }
  60         // Note: offset or count might be near -1>>>1.
  61         if (offset > codePoints.length - count) {
  62             throw new StringIndexOutOfBoundsException(offset + count);
  63         }
  64 
  65         final int end = offset + count;
  66 
  67         // Pass 1: Compute precise size of char[]
  68         int n = count;
  69         for (int i = offset; i < end; i++) {
  70             int c = codePoints[i];
  71             if (Character.isBmpCodePoint(c))
  72                 continue;
  73             else if (Character.isValidCodePoint(c))
  74                 n++;
  75             else throw new IllegalArgumentException(Integer.toString(c));
  76         }
  77 
  78         // Pass 2: Allocate and fill in char[]
  79         final char[] v = new char[n];
  80 
  81         for (int i = offset, j = 0; i < end; i++, j++) {
  82             int c = codePoints[i];
  83             if (Character.isBmpCodePoint(c))
  84                 v[j] = (char)c;
  85             else
  86                 Character.toSurrogates(c, v, j++);
  87         }
  88 
  89         this.value = v;
  90     }
  91 
  92     @Deprecated
  93     public String(byte ascii[], int hibyte, int offset, int count) {
  94         checkBounds(ascii, offset, count);
  95         char value[] = new char[count];
  96 
  97         if (hibyte == 0) {
  98             for (int i = count; i-- > 0;) {
  99                 value[i] = (char)(ascii[i + offset] & 0xff);
 100             }
 101         } else {
 102             hibyte <<= 8;
 103             for (int i = count; i-- > 0;) {
 104                 value[i] = (char)(hibyte | (ascii[i + offset] & 0xff));
 105             }
 106         }
 107         this.value = value;
 108     }
 109 
 110     @Deprecated
 111     public String(byte ascii[], int hibyte) {
 112         this(ascii, hibyte, 0, ascii.length);
 113     }
 114 
 115      private static void checkBounds(byte[] bytes, int offset, int length) {
 116         if (length < 0)
 117             throw new StringIndexOutOfBoundsException(length);
 118         if (offset < 0)
 119             throw new StringIndexOutOfBoundsException(offset);
 120         if (offset > bytes.length - length)
 121             throw new StringIndexOutOfBoundsException(offset + length);
 122     }
 123 
 124     public String(byte bytes[], int offset, int length, String charsetName)
 125             throws UnsupportedEncodingException {
 126         if (charsetName == null)
 127             throw new NullPointerException("charsetName");
 128         checkBounds(bytes, offset, length);
 129         this.value = StringCoding.decode(charsetName, bytes, offset, length);
 130     }
 131 
 132     public String(byte bytes[], int offset, int length, Charset charset) {
 133         if (charset == null)
 134             throw new NullPointerException("charset");
 135         checkBounds(bytes, offset, length);
 136         this.value =  StringCoding.decode(charset, bytes, offset, length);
 137     }
 138 
 139     public String(byte bytes[], String charsetName)
 140             throws UnsupportedEncodingException {
 141         this(bytes, 0, bytes.length, charsetName);
 142     }
 143 
 144     public String(byte bytes[], Charset charset) {
 145         this(bytes, 0, bytes.length, charset);
 146     }
 147 
 148     public String(byte bytes[], int offset, int length) {
 149         checkBounds(bytes, offset, length);
 150         this.value = StringCoding.decode(bytes, offset, length);
 151     }
 152 
 153     public String(byte bytes[]) {
 154         this(bytes, 0, bytes.length);
 155     }
 156 
 157     public String(StringBuffer buffer) {
 158         synchronized(buffer) {
 159             this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
 160         }
 161     }
 162 
 163     public String(StringBuilder builder) {
 164         this.value = Arrays.copyOf(builder.getValue(), builder.length());
 165     }
 166 
 167     String(char[] value, boolean share) {
 168         // assert share : "unshared not supported";
 169         this.value = value;
 170     }
 171 
 172     @Deprecated
 173     String(int offset, int count, char[] value) {
 174         this(value, offset, count);
 175     }
 176 
 177     public int length() {
 178         return value.length;
 179     }
 180 
 181     public boolean isEmpty() {
 182         return value.length == 0;
 183     }
 184 
 185     public char charAt(int index) {
 186         if ((index < 0) || (index >= value.length)) {
 187             throw new StringIndexOutOfBoundsException(index);
 188         }
 189         return value[index];
 190     }
 191 
 192     public int codePointAt(int index) {
 193         if ((index < 0) || (index >= value.length)) {
 194             throw new StringIndexOutOfBoundsException(index);
 195         }
 196         return Character.codePointAtImpl(value, index, value.length);
 197     }
 198 
 199     public int codePointBefore(int index) {
 200         int i = index - 1;
 201         if ((i < 0) || (i >= value.length)) {
 202             throw new StringIndexOutOfBoundsException(index);
 203         }
 204         return Character.codePointBeforeImpl(value, index, 0);
 205     }
 206 
 207     public int codePointCount(int beginIndex, int endIndex) {
 208         if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
 209             throw new IndexOutOfBoundsException();
 210         }
 211         return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
 212     }
 213 
 214     public int offsetByCodePoints(int index, int codePointOffset) {
 215         if (index < 0 || index > value.length) {
 216             throw new IndexOutOfBoundsException();
 217         }
 218         return Character.offsetByCodePointsImpl(value, 0, value.length,
 219                 index, codePointOffset);
 220     }
 221 
 222     void getChars(char dst[], int dstBegin) {
 223         System.arraycopy(value, 0, dst, dstBegin, value.length);
 224     }
 225 
 226     public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
 227         if (srcBegin < 0) {
 228             throw new StringIndexOutOfBoundsException(srcBegin);
 229         }
 230         if (srcEnd > value.length) {
 231             throw new StringIndexOutOfBoundsException(srcEnd);
 232         }
 233         if (srcBegin > srcEnd) {
 234             throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
 235         }
 236         System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
 237     }
 238 
 239     @Deprecated
 240     public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
 241         if (srcBegin < 0) {
 242             throw new StringIndexOutOfBoundsException(srcBegin);
 243         }
 244         if (srcEnd > value.length) {
 245             throw new StringIndexOutOfBoundsException(srcEnd);
 246         }
 247         if (srcBegin > srcEnd) {
 248             throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
 249         }
 250         int j = dstBegin;
 251         int n = srcEnd;
 252         int i = srcBegin;
 253         char[] val = value;   /* avoid getfield opcode */
 254 
 255         while (i < n) {
 256             dst[j++] = (byte)val[i++];
 257         }
 258     }
 259 
 260     public byte[] getBytes(String charsetName)
 261             throws UnsupportedEncodingException {
 262         if (charsetName == null) throw new NullPointerException();
 263         return StringCoding.encode(charsetName, value, 0, value.length);
 264     }
 265 
 266     public byte[] getBytes(Charset charset) {
 267         if (charset == null) throw new NullPointerException();
 268         return StringCoding.encode(charset, value, 0, value.length);
 269     }
 270 
 271     public byte[] getBytes() {
 272         return StringCoding.encode(value, 0, value.length);
 273     }
 274 
 275     public boolean equals(Object anObject) {
 276         if (this == anObject) {
 277             return true;
 278         }
 279         if (anObject instanceof String) {
 280             String anotherString = (String) anObject;
 281             int n = value.length;
 282             if (n == anotherString.value.length) {
 283                 char v1[] = value;
 284                 char v2[] = anotherString.value;
 285                 int i = 0;
 286                 while (n-- != 0) {
 287                     if (v1[i] != v2[i])
 288                             return false;
 289                     i++;
 290                 }
 291                 return true;
 292             }
 293         }
 294         return false;
 295     }
 296 
 297     public boolean contentEquals(StringBuffer sb) {
 298         synchronized (sb) {
 299             return contentEquals((CharSequence) sb);
 300         }
 301     }
 302 
 303     public boolean contentEquals(CharSequence cs) {
 304         if (value.length != cs.length())
 305             return false;
 306         // Argument is a StringBuffer, StringBuilder
 307         if (cs instanceof AbstractStringBuilder) {
 308             char v1[] = value;
 309             char v2[] = ((AbstractStringBuilder) cs).getValue();
 310             int i = 0;
 311             int n = value.length;
 312             while (n-- != 0) {
 313                 if (v1[i] != v2[i])
 314                     return false;
 315                 i++;
 316             }
 317             return true;
 318         }
 319         // Argument is a String
 320         if (cs.equals(this))
 321             return true;
 322         // Argument is a generic CharSequence
 323         char v1[] = value;
 324         int i = 0;
 325         int n = value.length;
 326         while (n-- != 0) {
 327             if (v1[i] != cs.charAt(i))
 328                 return false;
 329             i++;
 330         }
 331         return true;
 332     }
 333 
 334     public boolean equalsIgnoreCase(String anotherString) {
 335         return (this == anotherString) ? true
 336                 : (anotherString != null)
 337                 && (anotherString.value.length == value.length)
 338                 && regionMatches(true, 0, anotherString, 0, value.length);
 339     }
 340 
 341     public int compareTo(String anotherString) {
 342         int len1 = value.length;
 343         int len2 = anotherString.value.length;
 344         int lim = Math.min(len1, len2);
 345         char v1[] = value;
 346         char v2[] = anotherString.value;
 347 
 348         int k = 0;
 349         while (k < lim) {
 350             char c1 = v1[k];
 351             char c2 = v2[k];
 352             if (c1 != c2) {
 353                 return c1 - c2;
 354             }
 355             k++;
 356         }
 357         return len1 - len2;
 358     }
 359 
 360     public static final Comparator<String> CASE_INSENSITIVE_ORDER
 361                                          = new CaseInsensitiveComparator();
 362     private static class CaseInsensitiveComparator
 363             implements Comparator<String>, java.io.Serializable {
 364         // use serialVersionUID from JDK 1.2.2 for interoperability
 365         private static final long serialVersionUID = 8575799808933029326L;
 366 
 367         public int compare(String s1, String s2) {
 368             int n1 = s1.length();
 369             int n2 = s2.length();
 370             int min = Math.min(n1, n2);
 371             for (int i = 0; i < min; i++) {
 372                 char c1 = s1.charAt(i);
 373                 char c2 = s2.charAt(i);
 374                 if (c1 != c2) {
 375                     c1 = Character.toUpperCase(c1);
 376                     c2 = Character.toUpperCase(c2);
 377                     if (c1 != c2) {
 378                         c1 = Character.toLowerCase(c1);
 379                         c2 = Character.toLowerCase(c2);
 380                         if (c1 != c2) {
 381                             // No overflow because of numeric promotion
 382                             return c1 - c2;
 383                         }
 384                     }
 385                 }
 386             }
 387             return n1 - n2;
 388         }
 389     }
 390 
 391     public int compareToIgnoreCase(String str) {
 392         return CASE_INSENSITIVE_ORDER.compare(this, str);
 393     }
 394 
 395     public boolean regionMatches(int toffset, String other, int ooffset,
 396             int len) {
 397         char ta[] = value;
 398         int to = toffset;
 399         char pa[] = other.value;
 400         int po = ooffset;
 401         // Note: toffset, ooffset, or len might be near -1>>>1.
 402         if ((ooffset < 0) || (toffset < 0)
 403                 || (toffset > (long)value.length - len)
 404                 || (ooffset > (long)other.value.length - len)) {
 405             return false;
 406         }
 407         while (len-- > 0) {
 408             if (ta[to++] != pa[po++]) {
 409                 return false;
 410             }
 411         }
 412         return true;
 413     }
 414 
 415     public boolean regionMatches(boolean ignoreCase, int toffset,
 416             String other, int ooffset, int len) {
 417         char ta[] = value;
 418         int to = toffset;
 419         char pa[] = other.value;
 420         int po = ooffset;
 421         // Note: toffset, ooffset, or len might be near -1>>>1.
 422         if ((ooffset < 0) || (toffset < 0)
 423                 || (toffset > (long)value.length - len)
 424                 || (ooffset > (long)other.value.length - len)) {
 425             return false;
 426         }
 427         while (len-- > 0) {
 428             char c1 = ta[to++];
 429             char c2 = pa[po++];
 430             if (c1 == c2) {
 431                 continue;
 432             }
 433             if (ignoreCase) {
 434                 // If characters don't match but case may be ignored,
 435                 // try converting both characters to uppercase.
 436                 // If the results match, then the comparison scan should
 437                 // continue.
 438                 char u1 = Character.toUpperCase(c1);
 439                 char u2 = Character.toUpperCase(c2);
 440                 if (u1 == u2) {
 441                     continue;
 442                 }
 443                 // Unfortunately, conversion to uppercase does not work properly
 444                 // for the Georgian alphabet, which has strange rules about case
 445                 // conversion.  So we need to make one last check before
 446                 // exiting.
 447                 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
 448                     continue;
 449                 }
 450             }
 451             return false;
 452         }
 453         return true;
 454     }
 455 
 456     public boolean startsWith(String prefix, int toffset) {
 457         char ta[] = value;
 458         int to = toffset;
 459         char pa[] = prefix.value;
 460         int po = 0;
 461         int pc = prefix.value.length;
 462         // Note: toffset might be near -1>>>1.
 463         if ((toffset < 0) || (toffset > value.length - pc)) {
 464             return false;
 465         }
 466         while (--pc >= 0) {
 467             if (ta[to++] != pa[po++]) {
 468                 return false;
 469             }
 470         }
 471         return true;
 472     }
 473 
 474     public boolean startsWith(String prefix) {
 475         return startsWith(prefix, 0);
 476     }
 477 
 478     public boolean endsWith(String suffix) {
 479         return startsWith(suffix, value.length - suffix.value.length);
 480     }
 481 
 482     public int hashCode() {
 483         int h = hash;
 484         if (h == 0 && value.length > 0) {
 485             char val[] = value;
 486 
 487             for (int i = 0; i < value.length; i++) {
 488                 h = 31 * h + val[i];
 489             }
 490             hash = h;
 491         }
 492         return h;
 493     }
 494 
 495     public int indexOf(int ch) {
 496         return indexOf(ch, 0);
 497     }
 498 
 499     public int indexOf(int ch, int fromIndex) {
 500         final int max = value.length;
 501         if (fromIndex < 0) {
 502             fromIndex = 0;
 503         } else if (fromIndex >= max) {
 504             // Note: fromIndex might be near -1>>>1.
 505             return -1;
 506         }
 507 
 508         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
 509             // handle most cases here (ch is a BMP code point or a
 510             // negative value (invalid code point))
 511             final char[] value = this.value;
 512             for (int i = fromIndex; i < max; i++) {
 513                 if (value[i] == ch) {
 514                     return i;
 515                 }
 516             }
 517             return -1;
 518         } else {
 519             return indexOfSupplementary(ch, fromIndex);
 520         }
 521     }
 522 
 523     private int indexOfSupplementary(int ch, int fromIndex) {
 524         if (Character.isValidCodePoint(ch)) {
 525             final char[] value = this.value;
 526             final char hi = Character.highSurrogate(ch);
 527             final char lo = Character.lowSurrogate(ch);
 528             final int max = value.length - 1;
 529             for (int i = fromIndex; i < max; i++) {
 530                 if (value[i] == hi && value[i + 1] == lo) {
 531                     return i;
 532                 }
 533             }
 534         }
 535         return -1;
 536     }
 537 
 538     public int lastIndexOf(int ch) {
 539         return lastIndexOf(ch, value.length - 1);
 540     }
 541 
 542     public int lastIndexOf(int ch, int fromIndex) {
 543         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
 544             // handle most cases here (ch is a BMP code point or a
 545             // negative value (invalid code point))
 546             final char[] value = this.value;
 547             int i = Math.min(fromIndex, value.length - 1);
 548             for (; i >= 0; i--) {
 549                 if (value[i] == ch) {
 550                     return i;
 551                 }
 552             }
 553             return -1;
 554         } else {
 555             return lastIndexOfSupplementary(ch, fromIndex);
 556         }
 557     }
 558 
 559     private int lastIndexOfSupplementary(int ch, int fromIndex) {
 560         if (Character.isValidCodePoint(ch)) {
 561             final char[] value = this.value;
 562             char hi = Character.highSurrogate(ch);
 563             char lo = Character.lowSurrogate(ch);
 564             int i = Math.min(fromIndex, value.length - 2);
 565             for (; i >= 0; i--) {
 566                 if (value[i] == hi && value[i + 1] == lo) {
 567                     return i;
 568                 }
 569             }
 570         }
 571         return -1;
 572     }
 573 
 574     public int indexOf(String str) {
 575         return indexOf(str, 0);
 576     }
 577 
 578     public int indexOf(String str, int fromIndex) {
 579         return indexOf(value, 0, value.length,
 580                 str.value, 0, str.value.length, fromIndex);
 581     }
 582 
 583     static int indexOf(char[] source, int sourceOffset, int sourceCount,
 584             char[] target, int targetOffset, int targetCount,
 585             int fromIndex) {
 586         if (fromIndex >= sourceCount) {
 587             return (targetCount == 0 ? sourceCount : -1);
 588         }
 589         if (fromIndex < 0) {
 590             fromIndex = 0;
 591         }
 592         if (targetCount == 0) {
 593             return fromIndex;
 594         }
 595 
 596         char first = target[targetOffset];
 597         int max = sourceOffset + (sourceCount - targetCount);
 598 
 599         for (int i = sourceOffset + fromIndex; i <= max; i++) {
 600             /* Look for first character. */
 601             if (source[i] != first) {
 602                 while (++i <= max && source[i] != first);
 603             }
 604 
 605             /* Found first character, now look at the rest of v2 */
 606             if (i <= max) {
 607                 int j = i + 1;
 608                 int end = j + targetCount - 1;
 609                 for (int k = targetOffset + 1; j < end && source[j]
 610                         == target[k]; j++, k++);
 611 
 612                 if (j == end) {
 613                     /* Found whole string. */
 614                     return i - sourceOffset;
 615                 }
 616             }
 617         }
 618         return -1;
 619     }
 620 
 621     public int lastIndexOf(String str) {
 622         return lastIndexOf(str, value.length);
 623     }
 624 
 625     public int lastIndexOf(String str, int fromIndex) {
 626         return lastIndexOf(value, 0, value.length,
 627                 str.value, 0, str.value.length, fromIndex);
 628     }
 629 
 630     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
 631             char[] target, int targetOffset, int targetCount,
 632             int fromIndex) {
 633         /*
 634          * Check arguments; return immediately where possible. For
 635          * consistency, don't check for null str.
 636          */
 637         int rightIndex = sourceCount - targetCount;
 638         if (fromIndex < 0) {
 639             return -1;
 640         }
 641         if (fromIndex > rightIndex) {
 642             fromIndex = rightIndex;
 643         }
 644         /* Empty string always matches. */
 645         if (targetCount == 0) {
 646             return fromIndex;
 647         }
 648 
 649         int strLastIndex = targetOffset + targetCount - 1;
 650         char strLastChar = target[strLastIndex];
 651         int min = sourceOffset + targetCount - 1;
 652         int i = min + fromIndex;
 653 
 654         startSearchForLastChar:
 655         while (true) {
 656             while (i >= min && source[i] != strLastChar) {
 657                 i--;
 658             }
 659             if (i < min) {
 660                 return -1;
 661             }
 662             int j = i - 1;
 663             int start = j - (targetCount - 1);
 664             int k = strLastIndex - 1;
 665 
 666             while (j > start) {
 667                 if (source[j--] != target[k--]) {
 668                     i--;
 669                     continue startSearchForLastChar;
 670                 }
 671             }
 672             return start - sourceOffset + 1;
 673         }
 674     }
 675 
 676     public String substring(int beginIndex) {
 677         if (beginIndex < 0) {
 678             throw new StringIndexOutOfBoundsException(beginIndex);
 679         }
 680         int subLen = value.length - beginIndex;
 681         if (subLen < 0) {
 682             throw new StringIndexOutOfBoundsException(subLen);
 683         }
 684         return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
 685     }
 686 
 687     public String substring(int beginIndex, int endIndex) {
 688         if (beginIndex < 0) {
 689             throw new StringIndexOutOfBoundsException(beginIndex);
 690         }
 691         if (endIndex > value.length) {
 692             throw new StringIndexOutOfBoundsException(endIndex);
 693         }
 694         int subLen = endIndex - beginIndex;
 695         if (subLen < 0) {
 696             throw new StringIndexOutOfBoundsException(subLen);
 697         }
 698         return ((beginIndex == 0) && (endIndex == value.length)) ? this
 699                 : new String(value, beginIndex, subLen);
 700     }
 701 
 702     public CharSequence subSequence(int beginIndex, int endIndex) {
 703         return this.substring(beginIndex, endIndex);
 704     }
 705 
 706     public String concat(String str) {
 707         int otherLen = str.length();
 708         if (otherLen == 0) {
 709             return this;
 710         }
 711         int len = value.length;
 712         char buf[] = Arrays.copyOf(value, len + otherLen);
 713         str.getChars(buf, len);
 714         return new String(buf, true);
 715     }
 716 
 717     public String replace(char oldChar, char newChar) {
 718         if (oldChar != newChar) {
 719             int len = value.length;
 720             int i = -1;
 721             char[] val = value; /* avoid getfield opcode */
 722 
 723             while (++i < len) {
 724                 if (val[i] == oldChar) {
 725                     break;
 726                 }
 727             }
 728             if (i < len) {
 729                 char buf[] = new char[len];
 730                 for (int j = 0; j < i; j++) {
 731                     buf[j] = val[j];
 732                 }
 733                 while (i < len) {
 734                     char c = val[i];
 735                     buf[i] = (c == oldChar) ? newChar : c;
 736                     i++;
 737                 }
 738                 return new String(buf, true);
 739             }
 740         }
 741         return this;
 742     }
 743 
 744     public boolean matches(String regex) {
 745         return Pattern.matches(regex, this);
 746     }
 747 
 748     public boolean contains(CharSequence s) {
 749         return indexOf(s.toString()) > -1;
 750     }
 751 
 752     public String replaceFirst(String regex, String replacement) {
 753         return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
 754     }
 755 
 756     public String replaceAll(String regex, String replacement) {
 757         return Pattern.compile(regex).matcher(this).replaceAll(replacement);
 758     }
 759 
 760     public String replace(CharSequence target, CharSequence replacement) {
 761         return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
 762                 this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
 763     }
 764 
 765     public String[] split(String regex, int limit) {
 766         /* fastpath if the regex is a
 767          (1)one-char String and this character is not one of the
 768             RegEx's meta characters ".$|()[{^?*+\\", or
 769          (2)two-char String and the first char is the backslash and
 770             the second is not the ascii digit or ascii letter.
 771          */
 772         char ch = 0;
 773         if (((regex.value.length == 1 &&
 774              ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
 775              (regex.length() == 2 &&
 776               regex.charAt(0) == '\\' &&
 777               (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
 778               ((ch-'a')|('z'-ch)) < 0 &&
 779               ((ch-'A')|('Z'-ch)) < 0)) &&
 780             (ch < Character.MIN_HIGH_SURROGATE ||
 781              ch > Character.MAX_LOW_SURROGATE))
 782         {
 783             int off = 0;
 784             int next = 0;
 785             boolean limited = limit > 0;
 786             ArrayList<String> list = new ArrayList<>();
 787             while ((next = indexOf(ch, off)) != -1) {
 788                 if (!limited || list.size() < limit - 1) {
 789                     list.add(substring(off, next));
 790                     off = next + 1;
 791                 } else {    // last one
 792                     //assert (list.size() == limit - 1);
 793                     list.add(substring(off, value.length));
 794                     off = value.length;
 795                     break;
 796                 }
 797             }
 798             // If no match was found, return this
 799             if (off == 0)
 800                 return new String[]{this};
 801 
 802             // Add remaining segment
 803             if (!limited || list.size() < limit)
 804                 list.add(substring(off, value.length));
 805 
 806             // Construct result
 807             int resultSize = list.size();
 808             if (limit == 0)
 809                 while (resultSize > 0 && list.get(resultSize - 1).length() == 0)
 810                     resultSize--;
 811             String[] result = new String[resultSize];
 812             return list.subList(0, resultSize).toArray(result);
 813         }
 814         return Pattern.compile(regex).split(this, limit);
 815     }
 816 
 817     public String[] split(String regex) {
 818         return split(regex, 0);
 819     }
 820 
 821     public String toLowerCase(Locale locale) {
 822         if (locale == null) {
 823             throw new NullPointerException();
 824         }
 825 
 826         int firstUpper;
 827         final int len = value.length;
 828 
 829         /* Now check if there are any characters that need to be changed. */
 830         scan: {
 831             for (firstUpper = 0 ; firstUpper < len; ) {
 832                 char c = value[firstUpper];
 833                 if ((c >= Character.MIN_HIGH_SURROGATE)
 834                         && (c <= Character.MAX_HIGH_SURROGATE)) {
 835                     int supplChar = codePointAt(firstUpper);
 836                     if (supplChar != Character.toLowerCase(supplChar)) {
 837                         break scan;
 838                     }
 839                     firstUpper += Character.charCount(supplChar);
 840                 } else {
 841                     if (c != Character.toLowerCase(c)) {
 842                         break scan;
 843                     }
 844                     firstUpper++;
 845                 }
 846             }
 847             return this;
 848         }
 849 
 850         char[] result = new char[len];
 851         int resultOffset = 0;  /* result may grow, so i+resultOffset
 852                                 * is the write location in result */
 853 
 854         /* Just copy the first few lowerCase characters. */
 855         System.arraycopy(value, 0, result, 0, firstUpper);
 856 
 857         String lang = locale.getLanguage();
 858         boolean localeDependent =
 859                 (lang == "tr" || lang == "az" || lang == "lt");
 860         char[] lowerCharArray;
 861         int lowerChar;
 862         int srcChar;
 863         int srcCount;
 864         for (int i = firstUpper; i < len; i += srcCount) {
 865             srcChar = (int)value[i];
 866             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
 867                     && (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
 868                 srcChar = codePointAt(i);
 869                 srcCount = Character.charCount(srcChar);
 870             } else {
 871                 srcCount = 1;
 872             }
 873             if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
 874                 lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
 875             } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
 876                 lowerChar = Character.ERROR;
 877             } else {
 878                 lowerChar = Character.toLowerCase(srcChar);
 879             }
 880             if ((lowerChar == Character.ERROR)
 881                     || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
 882                 if (lowerChar == Character.ERROR) {
 883                     if (!localeDependent && srcChar == '\u0130') {
 884                         lowerCharArray =
 885                                 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
 886                     } else {
 887                         lowerCharArray =
 888                                 ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
 889                     }
 890                 } else if (srcCount == 2) {
 891                     resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
 892                     continue;
 893                 } else {
 894                     lowerCharArray = Character.toChars(lowerChar);
 895                 }
 896 
 897                 /* Grow result if needed */
 898                 int mapLen = lowerCharArray.length;
 899                 if (mapLen > srcCount) {
 900                     char[] result2 = new char[result.length + mapLen - srcCount];
 901                     System.arraycopy(result, 0, result2, 0, i + resultOffset);
 902                     result = result2;
 903                 }
 904                 for (int x = 0; x < mapLen; ++x) {
 905                     result[i + resultOffset + x] = lowerCharArray[x];
 906                 }
 907                 resultOffset += (mapLen - srcCount);
 908             } else {
 909                 result[i + resultOffset] = (char)lowerChar;
 910             }
 911         }
 912         return new String(result, 0, len + resultOffset);
 913     }
 914 
 915     public String toLowerCase() {
 916         return toLowerCase(Locale.getDefault());
 917     }
 918 
 919     public String toUpperCase(Locale locale) {
 920         if (locale == null) {
 921             throw new NullPointerException();
 922         }
 923 
 924         int firstLower;
 925         final int len = value.length;
 926 
 927         /* Now check if there are any characters that need to be changed. */
 928         scan: {
 929            for (firstLower = 0 ; firstLower < len; ) {
 930                 int c = (int)value[firstLower];
 931                 int srcCount;
 932                 if ((c >= Character.MIN_HIGH_SURROGATE)
 933                         && (c <= Character.MAX_HIGH_SURROGATE)) {
 934                     c = codePointAt(firstLower);
 935                     srcCount = Character.charCount(c);
 936                 } else {
 937                     srcCount = 1;
 938                 }
 939                 int upperCaseChar = Character.toUpperCaseEx(c);
 940                 if ((upperCaseChar == Character.ERROR)
 941                         || (c != upperCaseChar)) {
 942                     break scan;
 943                 }
 944                 firstLower += srcCount;
 945             }
 946             return this;
 947         }
 948 
 949         char[] result = new char[len]; /* may grow */
 950         int resultOffset = 0;  /* result may grow, so i+resultOffset
 951          * is the write location in result */
 952 
 953         /* Just copy the first few upperCase characters. */
 954         System.arraycopy(value, 0, result, 0, firstLower);
 955 
 956         String lang = locale.getLanguage();
 957         boolean localeDependent =
 958                 (lang == "tr" || lang == "az" || lang == "lt");
 959         char[] upperCharArray;
 960         int upperChar;
 961         int srcChar;
 962         int srcCount;
 963         for (int i = firstLower; i < len; i += srcCount) {
 964             srcChar = (int)value[i];
 965             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
 966                 (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
 967                 srcChar = codePointAt(i);
 968                 srcCount = Character.charCount(srcChar);
 969             } else {
 970                 srcCount = 1;
 971             }
 972             if (localeDependent) {
 973                 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
 974             } else {
 975                 upperChar = Character.toUpperCaseEx(srcChar);
 976             }
 977             if ((upperChar == Character.ERROR)
 978                     || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
 979                 if (upperChar == Character.ERROR) {
 980                     if (localeDependent) {
 981                         upperCharArray =
 982                                 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
 983                     } else {
 984                         upperCharArray = Character.toUpperCaseCharArray(srcChar);
 985                     }
 986                 } else if (srcCount == 2) {
 987                     resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
 988                     continue;
 989                 } else {
 990                     upperCharArray = Character.toChars(upperChar);
 991                 }
 992 
 993                 /* Grow result if needed */
 994                 int mapLen = upperCharArray.length;
 995                 if (mapLen > srcCount) {
 996                     char[] result2 = new char[result.length + mapLen - srcCount];
 997                     System.arraycopy(result, 0, result2, 0, i + resultOffset);
 998                     result = result2;
 999                 }
1000                 for (int x = 0; x < mapLen; ++x) {
1001                     result[i + resultOffset + x] = upperCharArray[x];
1002                 }
1003                 resultOffset += (mapLen - srcCount);
1004             } else {
1005                 result[i + resultOffset] = (char)upperChar;
1006             }
1007         }
1008         return new String(result, 0, len + resultOffset);
1009     }
1010 
1011     public String toUpperCase() {
1012         return toUpperCase(Locale.getDefault());
1013     }
1014 
1015     public String trim() {
1016         int len = value.length;
1017         int st = 0;
1018         char[] val = value;    /* avoid getfield opcode */
1019 
1020         while ((st < len) && (val[st] <= ' ')) {
1021             st++;
1022         }
1023         while ((st < len) && (val[len - 1] <= ' ')) {
1024             len--;
1025         }
1026         return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
1027     }
1028 
1029     public String toString() {
1030         return this;
1031     }
1032 
1033     public char[] toCharArray() {
1034         // Cannot use Arrays.copyOf because of class initialization order issues
1035         char result[] = new char[value.length];
1036         System.arraycopy(value, 0, result, 0, value.length);
1037         return result;
1038     }
1039 
1040     public static String format(String format, Object... args) {
1041         return new Formatter().format(format, args).toString();
1042     }
1043 
1044     public static String format(Locale l, String format, Object... args) {
1045         return new Formatter(l).format(format, args).toString();
1046     }
1047 
1048     public static String valueOf(Object obj) {
1049         return (obj == null) ? "null" : obj.toString();
1050     }
1051 
1052     public static String valueOf(char data[]) {
1053         return new String(data);
1054     }
1055 
1056     public static String valueOf(char data[], int offset, int count) {
1057         return new String(data, offset, count);
1058     }
1059 
1060     public static String copyValueOf(char data[], int offset, int count) {
1061         // All public String constructors now copy the data.
1062         return new String(data, offset, count);
1063     }
1064 
1065     public static String copyValueOf(char data[]) {
1066         return new String(data);
1067     }
1068 
1069     public static String valueOf(boolean b) {
1070         return b ? "true" : "false";
1071     }
1072 
1073     public static String valueOf(char c) {
1074         char data[] = {c};
1075         return new String(data, true);
1076     }
1077 
1078     public static String valueOf(int i) {
1079         return Integer.toString(i);
1080     }
1081 
1082     public static String valueOf(long l) {
1083         return Long.toString(l);
1084     }
1085 
1086     public static String valueOf(float f) {
1087         return Float.toString(f);
1088     }
1089 
1090     public static String valueOf(double d) {
1091         return Double.toString(d);
1092     }
1093 
1094     public native String intern();
1095 
1096     private static final int HASHING_SEED;
1097 
1098     static {
1099         long nanos = System.nanoTime();
1100         long now = System.currentTimeMillis();
1101         int SEED_MATERIAL[] = {
1102                 System.identityHashCode(String.class),
1103                 System.identityHashCode(System.class),
1104                 (int) (nanos >>> 32),
1105                 (int) nanos,
1106                 (int) (now >>> 32),
1107                 (int) now,
1108                 (int) (System.nanoTime() >>> 2)
1109         };
1110 
1111         // Use murmur3 to scramble the seeding material.
1112         // Inline implementation to avoid loading classes
1113         int h1 = 0;
1114 
1115         // body
1116         for (int k1 : SEED_MATERIAL) {
1117             k1 *= 0xcc9e2d51;
1118             k1 = (k1 << 15) | (k1 >>> 17);
1119             k1 *= 0x1b873593;
1120 
1121             h1 ^= k1;
1122             h1 = (h1 << 13) | (h1 >>> 19);
1123             h1 = h1 * 5 + 0xe6546b64;
1124         }
1125 
1126         // tail (always empty, as body is always 32-bit chunks)
1127 
1128         // finalization
1129 
1130         h1 ^= SEED_MATERIAL.length * 4;
1131 
1132         // finalization mix force all bits of a hash block to avalanche
1133         h1 ^= h1 >>> 16;
1134         h1 *= 0x85ebca6b;
1135         h1 ^= h1 >>> 13;
1136         h1 *= 0xc2b2ae35;
1137         h1 ^= h1 >>> 16;
1138 
1139         HASHING_SEED = h1;
1140     }
1141 
1142     private transient int hash32 = 0;
1143 
1144 
1145     int hash32() {
1146         int h = hash32;
1147         if (0 == h) {
1148            // harmless data race on hash32 here.
1149            h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length);
1150 
1151            // ensure result is not zero to avoid recalcing
1152            h = (0 != h) ? h : 1;
1153 
1154            hash32 = h;
1155         }
1156 
1157         return h;
1158     }
1159 }
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 }
View Code

 

 

posted on 2013-11-08 08:36  如果天空不死  阅读(114034)  评论(11编辑  收藏  举报