Java String Sub String subString(String srcStr, int subLen)

Here you can find the source of subString(String srcStr, int subLen)

Description

Description:Sub a string with the length,

License

Open Source License

Parameter

Parameter Description
srcStr source string
subLen the length what you want to sub a string

Return

subLen the length of sub string

Declaration

public static String subString(String srcStr, int subLen) 

Method Source Code

//package com.java2s;
/*//from w w w .  j a v  a2 s  . c o  m
 * $RCSfile: LogStringUtil,v $$
 * $Revision: 1.0  $
 * $Date: 2010-12-09  $
 *
 * Copyright (C) 2011 GyTech, Inc. All rights reserved.
 *
 * This software is the proprietary information of GyTech, Inc.
 * Use is subject to license terms.
 */

public class Main {
    /**
    * <p>Description:Sub a string with the length, </p>
    * @param srcStr source string
    * @param subLen the length what you want to sub a string
    * @return subLen the length of sub string
    */
    public static String subString(String srcStr, int subLen) {
        byte[] bytes = srcStr.getBytes();
        //add by yujie
        //when logwarn system will remove some character of chinese string
        //on 2005/10/18
        if (bytes.length <= subLen)
            return srcStr;

        char[] chars = srcStr.toCharArray();
        StringBuffer sb = new StringBuffer();

        for (int i = 0, j = 0; i < subLen && i < bytes.length && j < chars.length;) {
            char cbyte = (char) bytes[i];
            //normal English character
            if (cbyte == chars[j]) {
                sb.append(chars[j]);
                i++;
                j++;
            } else {//Chinese character
                    //if adding next Chinese character will be over limitted, 
                    //then will not add this character
                if (i + 1 < subLen) {
                    sb.append(chars[j]);
                    //one chinese character will be equal two bytes
                    i++;
                    i++;
                    j++;
                } else
                    break;
            }
        }

        return sb.toString();
    }
}

Related

  1. subString(String src, int startIndex, int endIndex)
  2. subString(String src, String begin, String end)
  3. substring(String src, String fromToken, String toToken)
  4. subString(String src, String start, String to)
  5. subString(String src, String start, String to)
  6. substring(String str, char pattern)
  7. substring(String str, int beginIndex)
  8. subString(String str, int beginIndex, int endIndex)
  9. substring(String str, int beginIndex, int endIndex)