Java实现字符串反转

Java实现字符串反转
 1 public String reverse(String src) {
 2         char[] value = src.toCharArray();
 3         int count = value.length;
 4         int n = count - 1;
 5         for (int j = (n - 1) >> 1; j >= 0; j--) {
 6             char tmp = value[j];
 7             char tmp2 = value[n - j];
 8             value[j] = tmp2;
 9             value[n - j] = tmp;
10         }
11         return new String(value);
12     }
Java实现字符串反转
替换原则:index k 的值和 n-k 的值进行交换。(始终记住程序员的n、k都是字符串的实际位置。)
乘除的最基本实现还是来源于移位操作。
Java字符串反转有2个已经实现的类函数: StringBuffer、StringBuilder类的函数reverse() 。
Java实现字符串反转
Java实现字符串反转
其中源码的实现如下,核心的思想是替换原则:
Java实现字符串反转
 1  /**
 2      * Causes this character sequence to be replaced by the reverse of
 3      * the sequence. If there are any surrogate pairs included in the
 4      * sequence, these are treated as single characters for the
 5      * reverse operation. Thus, the order of the high-low surrogates
 6      * is never reversed.
 7      *
 8      * Let <i>n</i> be the character length of this character sequence
 9      * (not the length in <code>char</code> values) just prior to
10      * execution of the <code>reverse</code> method. Then the
11      * character at index <i>k</i> in the new character sequence is
12      * equal to the character at index <i>n-k-1</i> in the old
13      * character sequence.
14      *
15      * <p>Note that the reverse operation may result in producing
16      * surrogate pairs that were unpaired low-surrogates and
17      * high-surrogates before the operation. For example, reversing
18      * "&#92;uDC00&#92;uD800" produces "&#92;uD800&#92;uDC00" which is
19      * a valid surrogate pair.
20      *
21      * @return  a reference to this object.
22      */
23     public AbstractStringBuilder reverse() {
24     boolean hasSurrogate = false;
25     int n = count - 1;
26     for (int j = (n-1) >> 1; j >= 0; --j) {
27         char temp = value[j];
28         char temp2 = value[n - j];
29         if (!hasSurrogate) {
30         hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
31             || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
32         }
33         value[j] = temp2;
34         value[n - j] = temp;
35     }
36     if (hasSurrogate) {
37         // Reverse back all valid surrogate pairs
38         for (int i = 0; i < count - 1; i++) {
39         char c2 = value[i];
40         if (Character.isLowSurrogate(c2)) {
41             char c1 = value[i + 1];
42             if (Character.isHighSurrogate(c1)) {
43             value[i++] = c1;
44             value[i] = c2;
45             }
46         }
47         }
48     }
49     return this;
50     }
View Code

其中的hasSurrogate与字符编码有关系,这个东东暂时没有研究。

Java实现字符串反转,布布扣,bubuko.com

Java实现字符串反转

上一篇:Javascript分号,加还是不加?


下一篇:JMir——Java版热血传奇2之资源文件与地图