Ejemplo n.º 1
0
  /**
   * If the line is short, this adds the line to StringArray. If the line is long, this splits the
   * line in 2 and adds both to StringArray.
   *
   * @param limit is the maximum number of characters per line
   * @param stringArray to capture the parts of s
   * @param s the string to be split (if needed) (if s == null or "", stringArray is unchanged).
   */
  private static void splitLine(int limit, StringArray stringArray, String s) {

    int limit10 = limit * 10;
    while (true) {
      if (s == null || s.length() == 0) return;

      int sLength = s.length();
      if (sLength <= limit * 2 / 3) { // short line is okay even if all caps
        stringArray.add(s);
        return;
      }

      // count through chars   noting more width of cap letters and digits, than avg letter
      int lastSpace = -1;
      int lastNonDigitChar = -1;
      int po = 0;
      int sum10 = 0;
      while (po < sLength && sum10 < limit10) {
        char ch = s.charAt(po);
        if (String2.isDigit(ch)) {
          sum10 += 14;
        } else if (String2.isLetter(ch)) {
          sum10 +=
              ch == 'C' || ch == 'M' || ch == 'S' || ch == 'W'
                  ? 16
                  : ch == 'c'
                          || ch == 'm'
                          || ch == 's'
                          || ch == 'w'
                          || ch == Character.toUpperCase(ch)
                      ? 15
                      : 10;
        } else if (ch == ' ') {
          sum10 += 8;
          lastSpace = po;
          lastNonDigitChar = po;
        } else if ("<>=_".indexOf(ch) >= 0) {
          sum10 += 17;
        } else {
          sum10 += 10;
          lastNonDigitChar = po;
        }
        po++;
      }

      // po == sLength is success
      // if just a few chars more, let it go
      if (po + 4 >= sLength) {
        stringArray.add(s);
        return;
      }

      // break at last space (or nonDigitLetter) before limit
      po =
          lastSpace >= limit * 3 / 4
              ? lastSpace
              : // preferred
              lastNonDigitChar >= limit / 2
                  ? lastNonDigitChar
                  : // next best
                  po; // worst case

      // add the string
      stringArray.add(s.substring(0, po + 1));

      // revamp s
      s = s.substring(po + 1).trim(); // remove leading space, if any
    }
  }