Java String Shorten shorten(String input)

Here you can find the source of shorten(String input)

Description

Shorten text to a character limit

License

Open Source License

Parameter

Parameter Description
String input

Return

String

Declaration

public static String shorten(String input) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   w ww  .  ja  v  a 2  s  . c om
     * Shorten text to a character limit
     *
     * @param String input
     * @return String
     */
    public static String shorten(String input) {
        if (140 > input.length()) {
            return input;
        }
        int charIndex;
        StringBuffer shortenedInput = new StringBuffer();
        for (charIndex = 0; charIndex < input.length(); charIndex++) {
            shortenedInput.append(input.charAt(charIndex));
            if (139 == charIndex) {
                break;
            }
        }

        while (charIndex < input.length()) {
            if (' ' == input.charAt(charIndex)) {
                shortenedInput.append("...");
                break;
            }
            if (('.' == input.charAt(charIndex))
                    && ((' ' == input.charAt(charIndex + 1)) || (charIndex + 1 == input.length()))) {
                shortenedInput.append(input.charAt(charIndex));
                break;
            } else if (('?' == input.charAt(charIndex))
                    && ((' ' == input.charAt(charIndex + 1)) || (charIndex + 1 == input.length()))) {
                shortenedInput.append(input.charAt(charIndex));
                break;
            } else if (('!' == input.charAt(charIndex))
                    && ((' ' == input.charAt(charIndex + 1)) || (charIndex + 1 == input.length()))) {
                shortenedInput.append(input.charAt(charIndex));
                break;
            }
            charIndex++;
        }

        return shortenedInput.toString();
    }
}

Related

  1. shorten(String className)
  2. shorten(String className)
  3. shorten(String clazz)
  4. shorten(String fullClassName)
  5. shorten(String in)
  6. shorten(String input, int length, boolean wholeWord)
  7. shorten(String label, int maxLength)
  8. shorten(String line)
  9. shorten(String msg, int front, String join, int end)