Java String Cut cutString(String str, int length, String charsetName)

Here you can find the source of cutString(String str, int length, String charsetName)

Description

cut String

License

Apache License

Declaration

public static String cutString(String str, int length, String charsetName) throws UnsupportedEncodingException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    public static String cutString(String str, int length, String charsetName) throws UnsupportedEncodingException {
        int len = str.getBytes(charsetName).length;
        if (len > length) {
            char[] chars = str.toCharArray();
            int i = 0;
            for (; i < chars.length; i++) {
                String tstr = new String(chars, 0, i + 1);
                if (tstr.getBytes(charsetName).length > length) {
                    i--;/*from  ww  w  .j av a 2s  .co  m*/
                    break;
                }
            }
            return new String(chars, 0, i + 1);
        }

        return str;
    }
}