截取字符串(中英混合串)-JAVA代码

来源:互联网 发布:宏观经济数据 编辑:程序博客网 时间:2024/06/10 13:54

public class SplitString {

    /**
     * @param args
     */
   
    public static void main(String[] args) {
        String str = "中Zell中国5000年,Congruations!";
        int bytes = 8;
        str = new SplitString().getSubString(str, bytes);
        System.out.println(str);
    }

 

        public String getSubString(String str,int bytes){
        int temp = bytes;
        byte [] AllBytes = str.getBytes();
        int AllStrByteLen = AllBytes.length;
        
        if(bytes > AllStrByteLen | bytes <= 0){
            return str;
        }
        int ChinaWordsNum = 0;
        for(int i=0;i<temp;i++){
            int IntOfByte = (int)AllBytes[i];

            if(IntOfByte < 0 ){
                ChinaWordsNum+=1;
            }

        }
        if(ChinaWordsNum%2 == 0){
            return  new String(AllBytes,0,temp);
        }else{
            if(bytes == 1){
                return null;
            }
        }
        return new String(AllBytes,0,temp-1);
    }

 

    public String getSubString(String SubjectString, int start, int length){ 
          String   ResultString   =   null; 
          try   { 
              Pattern regex = Pattern.compile("^.{" + start + "}(.{" + length + "}).*$"); 
              Matcher regexMatcher = regex.matcher(SubjectString); 
              System.out.println(regexMatcher.matches()); 
              try   { 
                  ResultString   =   regexMatcher.replaceAll("$1"); 
              }   catch   (IllegalArgumentException ex){ 
                 
              }   catch   (IndexOutOfBoundsException ex){ 
                 
              }   
          }catch(PatternSyntaxException ex){
             
          }
              return   ResultString; 
          }  
}

原创粉丝点击