Word wraps a <code>String</code> to be no longer than the provided number of characters wide.

TODO: Make this more efficient by eliminating the internal use of substring.
348747
public static void wordWrap(String string, int width, Appendable out) throws IOException {
		width++;
		boolean useCR = false;
		do {
			int pos = string.indexOf('\n');
			if (!useCR && pos > 0 && string.charAt(pos - 1) == '\r') useCR = true;
			int linelength = pos == -1 ? string.length() : pos + 1;
			if ((pos==-1?linelength-1:pos) <= width) {
				// No wrap required
				out.append(string, 0, linelength);
				string = string.substring(linelength);
			} else {
				// Word wrap required

				// Search for the beginning of the first word that is past the <code>width</code> column
				// The wrap character must be on the same line as the outputted line.
				int lastBreakChar = 0;

				for (int c = 0; c < width; c++) {
					// Check to see if it is a break character
					char ch = string.charAt(c);
					boolean isBreak = false;
					for (int d = 0; d < wordWrapChars.length; d++) {
						if (ch == wordWrapChars[d]) {
							isBreak = true;
							break;
						}
					}
					if (isBreak) lastBreakChar = c + 1;
				}

				// If no break has been found, keep searching until a break is found
				if (lastBreakChar == 0) {
					for (int c = width; c < linelength; c++) {
						char ch = string.charAt(c);
						boolean isBreak = false;
						for (int d = 0; d < wordWrapChars.length; d++) {
							if (ch == wordWrapChars[d]) {
								isBreak = true;
								break;
							}
						}
						if (isBreak) {
							lastBreakChar = c + 1;
							break;
						}
					}
				}

				if (lastBreakChar == 0) {
					// Take the whole line
					out.append(string, 0, linelength);
					string = string.substring(linelength);
				} else {
					// Break out the section
					out.append(string, 0, lastBreakChar);
					if(useCR) out.append("\r\n");
					else out.append('\n');
					string = string.substring(lastBreakChar);
				}
			}
		} while (string.length() > 0);
	}
239531
public static function utf8WordWrap(string $string, int $width = 75, string $sep = "\n", bool $cut = false): string
    {
        $out = '';
        while ($string) {
            if (mb_strlen($string) <= $width) {
                // Do not wrap any text that is less than the output area.
                $out .= $string;
                $string = '';
            } else {
                $sub1 = mb_substr($string, 0, $width + 1);
                if (mb_substr($string, mb_strlen($sub1) - 1, 1) == ' ') {
                    // include words that end by a space immediately after the area.
                    $sub = $sub1;
                } else {
                    $sub = mb_substr($string, 0, $width);
                }
                $spacepos = strrpos($sub, ' ');
                if ($spacepos === false) {
                    // No space on line?
                    if ($cut) {
                        $out .= $sub . $sep;
                        $string = mb_substr($string, mb_strlen($sub));
                    } else {
                        $spacepos = strpos($string, ' ');
                        if ($spacepos === false) {
                            $out    .= $string;
                            $string = '';
                        } else {
                            $out    .= substr($string, 0, $spacepos) . $sep;
                            $string = substr($string, $spacepos + 1);
                        }
                    }
                } else {
                    // Split at space;
                    $out .= substr($string, 0, $spacepos) . $sep;
                    $string = substr($string, $spacepos + 1);
                }
            }
        }

        return $out;
    }
375487
def rewrap_long(s, width=COLS):
    
    paras = s.split('\n\n')
    return '\n\n'.join(rewrap(p) for p in paras)
849809
private String cleanAndTrimString(String text, int maxTextLength) {
        if (StringUtils.isNotBlank(text)) {
            String cleaned = text.trim().replaceAll("[\\s]+", " ");
            return cleaned.length() <= maxTextLength
                    ? cleaned
                    : cleaned.substring(0, maxTextLength) + " ...";
        }
        return text;
    }
414763
function(text, length, moreText) {
    var t = text.split('</p>');
    return t.length < length ? text : t.slice(0, length).join('</p>') + '</p>' + moreText;
  }
1079274
def encode_string_with_trailing_spaces(string, target_length)
      length = string.length
      if length < target_length
        return "#{[string].pack(@str)}#{['20'*(target_length-length)].pack(@hex)}"
      elsif length == target_length
        return [string].pack(@str)
      else
        raise "The specified string is longer than the allowed maximum length (String: #{string}, Target length: #{target_length})."
      end
    end
1180872
public static String truncate (String text, int length, String append)
    {
        return StringUtil.truncate(text, length, append);
    }
611509
public final long fromBitString2Long(String str) {
        if (str.length() > 64)
            throw new UnsupportedOperationException("Strings needs to fit into a 'long' but length was " + str.length());

        long res = 0;
        int strLen = str.length();
        for (int charIndex = 0; charIndex < strLen; charIndex++) {
            res <<= 1;
            if (str.charAt(charIndex) != '0')
                res |= 1;
        }
        res <<= (64 - strLen);
        return res;
    }
833249
private static String wordShapeChris2Short(String s, int len, Collection<String> knownLCWords) {
    int sbLen = (knownLCWords != null) ? len + 1: len;  // markKnownLC makes String 1 longer
    final StringBuilder sb = new StringBuilder(sbLen);
    boolean nonLetters = false;

    for (int i = 0; i < len; i++) {
      char c = s.charAt(i);
      char m = c;
      if (Character.isDigit(c)) {
        m = 'd';
      } else if (Character.isLowerCase(c)) {
        m = 'x';
      } else if (Character.isUpperCase(c) || Character.isTitleCase(c)) {
        m = 'X';
      }
      for (String gr : greek) {
        if (s.startsWith(gr, i)) {
          m = 'g';
          //System.out.println(s + "  ::  " + s.substring(i+1));
          i += gr.length() - 1;
          // System.out.println("Position skips to " + i);
          break;
        }
      }
      if (m != 'x' && m != 'X') {
        nonLetters = true;
      }

      sb.append(m);
    }

    if (knownLCWords != null) {
      if ( ! nonLetters && knownLCWords.contains(s.toLowerCase())) {
        sb.append('k');
      }
    }
    // System.out.println(s + " became " + sb);
    return sb.toString();
  }
1264360
private static String wrapLine(String str, int wrapTextLength) {
	int wtl = wrapTextLength;

	if (str.length() <= wtl) return str;

	String sub = str.substring(0, wtl);
	String rest = str.substring(wtl);
	char firstR = rest.charAt(0);
	String ls = SystemUtil.getOSSpecificLineSeparator();

	if (firstR == ' ' || firstR == '\t') return sub + ls + wrapLine(rest.length() > 1 ? rest.substring(1) : "", wrapTextLength);

	int indexSpace = sub.lastIndexOf(' ');
	int indexTab = sub.lastIndexOf('\t');
	int index = indexSpace <= indexTab ? indexTab : indexSpace;

	if (index == -1) return sub + ls + wrapLine(rest, wrapTextLength);
	return sub.substring(0, index) + ls + wrapLine(sub.substring(index + 1) + rest, wrapTextLength);

    }
432687
def shorten(string, maxlen):
    """"""
    if 1 < maxlen < len(string):
        string = string[:maxlen - 1] + u'…'
    return string[:maxlen]
511142
function endsWith(longStr, shortStr) {
		var longLen = longStr.length, shortLen = shortStr.length;
		return (longLen >= shortLen) &&
			(longStr.substr(longLen - shortLen) === shortStr);
	}
865163
public static String truncate(String string, int maxLength) {
        if (string.length() > maxLength) {
            return string.substring(0, maxLength);
        }
        return string;
    }
1019185
private static String trimTrailingWhitespace(String string) {
        int end = 0;
        char c;

        for (int i = string.length() - 1; i >= 0; i--) {
            c = string.charAt(i);
            if (!Character.isWhitespace(c)) {
                end = i;
                break;
            }
        }

        if (end == 0) {
            return string;
        }

        return string.substring(0, end + 1);
    }
174022
def truncate(string, options = {})
      length = options[:length] || 30

      if string.length > length
        string[0..length - 3] + "..."
      else
        string
      end
    end
657637
function(string, maxLength) {
            if (!string) return string;
            if (maxLength < 1) return string;
            if (string.length <= maxLength) return string;
            if (maxLength == 1) return string.substring(0,1) + '...';

            var midpoint = Math.ceil(string.length / 2);
            var toremove = string.length - maxLength;
            var lstrip = Math.ceil(toremove/2);
            var rstrip = toremove - lstrip;
            return string.substring(0, midpoint-lstrip) + '...' + string.substring(midpoint+rstrip);
        }
163015
def shorten_string(string, max_width):
    ''' 
    '''
    string_len = len(string)
    if string_len <= max_width:
        return string
    visible = max_width - 16 - int(log10(string_len))
    # expected suffix len "...(and XXXXX more)"
    if not isinstance(string, unistr):
        visstring = unistr(string[:visible], errors='ignore')
    else:
        visstring = string[:visible]
    return u''.join((visstring, u'...(and ',
                     unistr(string_len - visible), u' more)'))