• 重写java.lang.String IndexOf()方法,实现对字符串以ASCII规则截取


     1     /**
     2      * 根据元数据和目标ascii位数截取字符串,失败返回-1
     3      * @param sourceStr    元数据字符串    
     4      * @param endIndex    截取到第几位
     5      * @return 结果字符串
     6      */
     7     public static String indexOf(String sourceStr,int endIndex){
     8         int length = 0;
     9         StringBuilder result = new StringBuilder();
    10         List<String> resultList = new ArrayList<String>(); 
    11         for(int i = 0; i < sourceStr.length(); i++){
    12             int ascii = Character.codePointAt(sourceStr,i);
    13             if(ascii >= 0 && ascii <=255){
    14                 length++;
    15                 resultList.add(String.valueOf(ascii));
    16             }else{
    17                 length+=2;
    18                 resultList.add(String.valueOf(ascii));
    19             }
    20             if(length>0){
    21                 if((length==sourceStr.length() && length <= endIndex) || length == endIndex || length == endIndex-1){
    22                     for (String string : resultList) {
    23                         result.append(asciiToString(string));
    24                     }
    25                     return result.toString();
    26                 }
    27             }
    28         }
    29         //return String.valueOf("-1");
    30         /**
    31          * 根据业务要求,如果传进来的参数为空值的时候默认返回空字符串
    32          */
    33         return "";
    34     }
    35     
    36     /**
    37      * 将ascii码转换为utf-8
    38      * @param value ascii编码 多个以,号分割
    39      * @return 结果字符串
    40      */
    41     public static String asciiToString(String value) {
    42         StringBuffer sbu = new StringBuffer();
    43         String[] chars = value.split(",");
    44         for (int i = 0; i < chars.length; i++) {
    45             sbu.append((char) Integer.parseInt(chars[i]));
    46         }
    47         return sbu.toString();
    48     }
  • 相关阅读:
    Path Sum
    Intersection of Two Linked Lists (求两个单链表的相交结点)
    Nginx入门资料
    赛马问题
    翻转单词顺序 VS 左旋转字符串
    重建二叉树
    Fibonacci相关问题
    Find Minimum in Rotated Sorted Array(旋转数组的最小数字)
    常用查找算法总结
    Contains Duplicate
  • 原文地址:https://www.cnblogs.com/john69-/p/8360760.html
Copyright © 2020-2023  润新知