Java String Abbreviate abbr(String str, int length)

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

Description

abbr

License

Open Source License

Declaration

public static String abbr(String str, int length) 

Method Source Code

//package com.java2s;
/**//from   www. j a v a  2  s  . co m
 * Copyright &copy; 2012-2013 <a href="https://github.com/Dopas/dopas">Dopas</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

import java.io.UnsupportedEncodingException;

public class Main {

    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : str.toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";

    }
}

Related

  1. abbrev(String longString, int size)
  2. abbrev(String result, int maxLength, String separator)
  3. abbreviate(final String str)
  4. abbreviate(final String str, final int maxWidth)