简体   繁体   中英

Limit the number of characters in one line of String in java

I want my one line to contain a maximum 69 characters without breaking words.

Suppose my string is as follows

\n TEXT\n TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXTEXTRA\n TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT

My output should be

\n
TEXT\n
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n 
TEXTEXTRA\n
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT

I don't want to count \n while counting characters and I don't want to break-word in between.

any word beyond or at the 69th character should come to the next line.

Sometimes \n may not appear in string still I want to split string at 69th character.

My code is as follows

public static char[] createLineofMaximumNumberOfChars(char[] textArray) {
        int count = 1;
        int j = 0;
        for (int i = 0; i < textArray.length; i++) {

            if (textArray[i] == '\n' && count != maxNoOfCharPerRow) {
                count = 1;
                j = i;
            } else if (textArray[i] != '\n') {
                count++;
            }

            if (count == maxNoOfCharPerRow) {
                j = j + count;
                if (i == textArray.length - 2)
                    continue;
                if (j < textArray.length - 1) {
                    if (textArray[j] == '\n' || textArray[j + 1] == '\n') {
                        count = 1;
                        continue;
                    }

                }
                while (j >= 0 && !Character.isWhitespace(textArray[j])) {
                    j--;
                }
                if (j >= 0) {
                    textArray[j] = '\n';
                    count = 1;
                }
            }

        }

        return textArray;
    }

You can do this using String#split() method on both "\n" in one for loop and again on whitespace in an inner for loop, for example:

String txt = "\n"
           + "TEXT\n"
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXTEXTRA\n"
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n"
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT\n"
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT";
    
boolean hasNewLine = txt.contains("\n");
String[] textParts = (hasNewLine ? txt.split("\n") : new String[] {txt});
StringBuilder finalString = new StringBuilder("");
for (int i = 0; i < textParts.length; i++) {
    if (textParts[i].length() > 69) {
        StringBuilder sb = new StringBuilder("");
        String[] words = textParts[i].split("\\s+");
        for (int j = 0; j < words.length; j++) {
            if ((sb.toString().length() + words[j].length()) > 69) {
                // Line must be filled since current word won't fit....
                sb.append(System.lineSeparator()); 
                if (hasNewLine) {
                    // Specific format required...
                    finalString.append(sb.toString()).append(words[j]).append(System.lineSeparator());
                }
                else {
                    finalString.append(sb.toString());  // place completed line into finalString
                    sb.delete(0, sb.capacity());        // empty the StringBuilder object so to start new line
                    sb.append(words[j]);                // set in the current word that didn't fit previous line.
                }
            }
            else {
                if (!sb.toString().isEmpty()) {
                    sb.append(" ");
                }
                sb.append(words[j]);
            }
        }
        // if sb contains words when loop finishes then append them to finalString.
        if (!hasNewLine && !sb.toString().isEmpty()) {
            finalString.append(sb.toString());
        }
    }
    else {
        // If the supplied String doesn't contain more than 69 characters
        // then append it to finalString.
        finalString.append(textParts[i])
                .append((i < (textParts.length - 1) ? System.lineSeparator() : ""));
    }
}

// Print the result to console.
System.out.println(finalString.toString());

The console window will display the generated string as:

TEXT
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXTEXTRA
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT

EDIT: As per Comment: ↓↓↓

what if \n is not present in the string and still I want to trim line at 69th character – Pawan Patil

If the newline ( \n ) character is not contained within the string then we must assume that the supplied string is nothing more than a whitespace delimited string and the code will process it accordingly via the inner loop. There are however some small changes that need to be done to accommodate this particular situation so that the overall code can handle either or.

A boolean flag ( hasNewLine ) is used to indicate whether or not newline characters ( \n ) are contained within the string. If true then the string is split based on the newline character and each element from this split is processed accordingly (as before) with the inner for loop.

If however there are no newline characters within the supplied String then the boolean flag, hasNewLine , will contain false and the textParts string array will contain only one element, the entire supplied string. A Ternary Operator is used to determine what this array is to hold, for example:

String[] textParts = (hasNewLine ? txt.split("\n") : new String[] {txt});

As you can now see, the hasNewLine boolean flag is also utilized within the inner for loop due to the fact that originally a specific output result format was and still is required. This inner loop needs to accommodate the different situations.

Updated code has be applied above so to accommodate your comment. Now, if a string is supplied as indicated in your post you will be displayed within the console window your desired posted result. If on the other hand a white-spaced delimited string is supplied as show below with no newline characters:

String txt = "TEXT "
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXTEXTRA "
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT "
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT "
           + "TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT";

then when processed will display within the console window the following:

TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXTEXTRA TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT
TEXT TEXT

updated devilshnd's answer so it would work even if no "\n" is present

 public static char[] answer(char[] textArray){
    String s = new String(textArray);
    boolean isNewLinePresent  = s.contains("\n");
    int count = 1;
    int maxNoOfCharPerRow = 69;
   if(isNewLinePresent) {
       int j = 0;
       for (int i = 0; i < textArray.length; i++) {

           if (textArray[i] == '\n' && count != maxNoOfCharPerRow) {
               count = 1;
               j = i;
           } else if (textArray[i] != '\n') {
               count++;
           }

           if (count == maxNoOfCharPerRow) {
               j = j + count;
               if (i == textArray.length - 2)
                   continue;
               if (j < textArray.length - 1) {
                   if (textArray[j] == '\n' || textArray[j + 1] == '\n') {
                       count = 1;
                       continue;
                   }

               }
               while (j >= 0 && !Character.isWhitespace(textArray[j])) {
                   j--;
               }
               if (j >= 0) {
                   textArray[j] = '\n';
                   count = 1;
               }
           }

       }
   }

   else {
       count = maxNoOfCharPerRow;
       while (count<=s.length() && textArray.length>maxNoOfCharPerRow && !(s.charAt(s.length()-1)=='\n')){
           System.out.println(count);
           s = s.substring(0, count) + "\n" + s.substring(count);
           count = count + maxNoOfCharPerRow + 1;
       }
       textArray = s.toCharArray();
   }
    return textArray;


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM