当前位置: 移动技术网 > IT编程>开发语言>Java > Java反转字符串和相关字符编码的问题解决

Java反转字符串和相关字符编码的问题解决

2019年07月22日  | 移动技术网IT编程  | 我要评论

亟须,南通理工学院教务系统,国企改革概念股有哪些

复制代码 代码如下:

public string reverse(char[] value){
       for (int i = (value.length - 1) >> 1; i >= 0; i--){
           char temp = value[i];
           value[i] = value[value.length - 1 - i];
           value[value.length - 1 - i] = temp;
       }
       return new string(value);
}

这样的代码,在算法方面是没有任何问题的。但是今天在查看stringbuffer源代码的时候发现,其中reverse方法的源代码写的很精妙。源代码如下:

复制代码 代码如下:

public abstractstringbuilder reverse() {
    boolean hassurrogate = false;
    int n = count - 1;
    for (int j = (n-1) >> 1; j >= 0; --j) {
        char temp = value[j];
        char temp2 = value[n - j];
        if (!hassurrogate) {
       hassurrogate = (temp >= character.min_surrogate && temp <= character.max_surrogate)
           || (temp2 >= character.min_surrogate && temp2 <= character.max_surrogate);
         }
         value[j] = temp2;
         value[n - j] = temp;
     }
     if (hassurrogate) {
         // reverse back all valid surrogate pairs
          for (int i = 0; i < count - 1; i++) {
             char c2 = value[i];
             if (character.islowsurrogate(c2)) {
                 char c1 = value[i + 1];
                 if (character.ishighsurrogate(c1)) {
                 value[i++] = c1;
                 value[i] = c2;
             }
         }
         }
     }
     return this;
 }

这个方法是定义在stringbuffer的父类abstractstringbuilder中的,所以该方法的返回值是abstractstringbuilder,在子类中调用的方式如下:
复制代码 代码如下:

public synchronized stringbuffer reverse() {
    super.reverse();
    return this;
}

从方法的内容来看,源代码中的基本思路是一致的,同样采用遍历一半字符串,然后将每个字符与其对应的字符进行交换。但是有不同之处,就是要判断每个字符是否在character.min_surrogate(\ud800)和character.max_surrogate(\udfff)之间。如果发现整个字符串中含有这种情况,则再次从头至尾遍历一次,同时判断value[i]是否满足character.islowsurrogate(),如果满足的情况下,继续判断value[i+1]是否满足character.ishighsurrogate(),如果也满足这种情况,则将第i位和第i+1位的字符互换。可能有的人会疑惑,为什么要这么做,因为java中的字符已经采用unicode代码,每个字符可以放下一个汉字。为什么还要这么做?
一个完整的 unicode 字符叫代码点codepoint,而一个 java char 叫 代码单元 code unit。string 对象以utf-16保存 unicode 字符,需要用2个字符表示一个超大字符集的汉字,这这种表示方式称之为 surrogate,第一个字符叫 surrogate high,第二个就是 surrogate low。具体需要注意的事宜如下:
判断一个char是否是surrogate区的字符,用character的 ishighsurrogate()/islowsurrogate()方法即可判断。从两个surrogate high/low 字符,返回一个完整的 unicode codepoint 用 character.tocodepoint()/codepointat()方法。
  一个code point,可能需要一个也可能需要两个char表示,因此不能直接使用 charsequence.length()方法直接返回一个字符串到底有多少个汉字,而需要用string.codepointcount()/character.codepointcount()。
 要定位字符串中的第n个字符,不能直接将n作为偏移量,而需要从字符串头部依次遍历得到,需要用string/character.offsetbycodepoints() 方法。
从字符串的当前字符,找到上一个字符,也不能直接用offset-- 实现,而需要用 string.codepointbefore()/character.codepointbefore(),或用 string/character.offsetbycodepoints()
 从当前字符,找下一个字符,不能直接用 offset++实现,需要判断当前 codepoint的长度后,再计算得到,或用string/character.offsetbycodepoints()。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网