Here you can find the source of subString(String srcStr, int subLen)
Description:Sub a string with the length,
Parameter | Description |
---|---|
srcStr | source string |
subLen | the length what you want to sub a string |
public static String subString(String srcStr, int subLen)
//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(); } }