web-dev-qa-db-fra.com

Grande chaîne divisée en lignes de longueur maximale en java

String input = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011.";

//text copied from http://www.nationalgeographic.com/community/terms/

Je souhaite diviser cette grande chaîne en lignes et les lignes ne doivent pas contenir plus de MAX_LINE_LENGTH caractères dans chaque ligne.

Ce que j'ai essayé jusqu'à présent

int MAX_LINE_LENGTH = 20;    
System.out.print(Arrays.toString(input.split("(?<=\\G.{MAX_LINE_LENGTH})")));
//maximum length of line 20 characters

Sortie:

[THESE TERMS AND COND, ITIONS OF SERVICE (t, he Terms) ARE A LEGA, L AND B ...

Cela provoque rupture de mots. Je ne veux pas ça. Au lieu de je veux obtenir une sortie comme celle-ci:

[THESE TERMS AND , CONDITIONS OF , SERVICE (the Terms) , ARE A LEGAL AND B ...

ne condition supplémentaire ajoutée: Si la longueur d'un mot est supérieure à MAX_LINE_LENGTH, le mot doit être divisé.

Et la solution devrait être sans l'aide de pots externes.

23
Abhishek

Parcourez simplement la chaîne mot par mot et coupez chaque fois qu'un mot dépasse la limite.

public String addLinebreaks(String input, int maxLineLength) {
    StringTokenizer tok = new StringTokenizer(input, " ");
    StringBuilder output = new StringBuilder(input.length());
    int lineLen = 0;
    while (tok.hasMoreTokens()) {
        String Word = tok.nextToken();

        if (lineLen + Word.length() > maxLineLength) {
            output.append("\n");
            lineLen = 0;
        }
        output.append(Word);
        lineLen += Word.length();
    }
    return output.toString();
}

Je viens de taper ça à main levée, vous devrez peut-être pousser et pousser un peu pour le faire compiler.

Bug: si un mot dans l'entrée est plus long que maxLineLength, il sera ajouté à la ligne actuelle au lieu d'une ligne trop longue. Je suppose que la longueur de votre ligne est de 80 ou 120 caractères, auquel cas il est peu probable que ce soit un problème.

26
Barend

Meilleur: utilisez Apache Commons Lang:

org.Apache.commons.lang.WordUtils

/**
 * <p>Wraps a single line of text, identifying words by <code>' '</code>.</p>
 * 
 * <p>New lines will be separated by the system property line separator.
 * Very long words, such as URLs will <i>not</i> be wrapped.</p>
 * 
 * <p>Leading spaces on a new line are stripped.
 * Trailing spaces are not stripped.</p>
 *
 * <pre>
 * WordUtils.wrap(null, *) = null
 * WordUtils.wrap("", *) = ""
 * </pre>
 *
 * @param str  the String to be Word wrapped, may be null
 * @param wrapLength  the column to wrap the words at, less than 1 is treated as 1
 * @return a line with newlines inserted, <code>null</code> if null input
 */
public static String wrap(String str, int wrapLength) {
    return wrap(str, wrapLength, null, false);
}
11
Saad Benbouzid

Vous pouvez utiliser la méthode WordUtils.wrap de Apache Commans Lang

 import Java.util.*;
 import org.Apache.commons.lang3.text.WordUtils;
 public class test3 {


public static void main(String[] args) {

    String S = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011.";
    String F = WordUtils.wrap(S, 20);
    String[] F1 =  F.split(System.lineSeparator());
    System.out.println(Arrays.toString(F1));

}}

Production

   [THESE TERMS AND, CONDITIONS OF, SERVICE (the Terms), ARE A LEGAL AND, BINDING AGREEMENT, BETWEEN YOU AND, NATIONAL GEOGRAPHIC, governing your use, of this site,, www.nationalgeographic.com,, which includes but, is not limited to, products, software, and services offered, by way of the, website such as the, Video Player,, Uploader, and other, applications that, link to these Terms, (the Site). Please, review the Terms, fully before you, continue to use the, Site. By using the, Site, you agree to, be bound by the, Terms. You shall, also be subject to, any additional terms, posted with respect, to individual, sections of the, Site. Please review, our Privacy Policy,, which also governs, your use of the, Site, to understand, our practices. If, you do not agree,, please discontinue, using the Site., National Geographic, reserves the right, to change the Terms, at any time without, prior notice. Your, continued access or, use of the Site, after such changes, indicates your, acceptance of the, Terms as modified., It is your, responsibility to, review the Terms, regularly. The Terms, were last updated on, 18 July 2011.]
7
Ravichandra

Merci Barend Garvelink pour votre réponse. J'ai modifié le code ci-dessus pour corriger le bug: "si un mot dans l'entrée est plus long que maxCharInLine"

public String[] splitIntoLine(String input, int maxCharInLine){

    StringTokenizer tok = new StringTokenizer(input, " ");
    StringBuilder output = new StringBuilder(input.length());
    int lineLen = 0;
    while (tok.hasMoreTokens()) {
        String Word = tok.nextToken();

        while(Word.length() > maxCharInLine){
            output.append(Word.substring(0, maxCharInLine-lineLen) + "\n");
            Word = Word.substring(maxCharInLine-lineLen);
            lineLen = 0;
        }

        if (lineLen + Word.length() > maxCharInLine) {
            output.append("\n");
            lineLen = 0;
        }
        output.append(Word + " ");

        lineLen += Word.length() + 1;
    }
    // output.split();
    // return output.toString();
    return output.toString().split("\n");
}
6
Rakesh Soni

À partir de la suggestion de @Barend, voici ma version finale avec des modifications mineures:

private static final char NEWLINE = '\n';
private static final String SPACE_SEPARATOR = " ";
//if text has \n, \r or \t symbols it's better to split by \s+
private static final String SPLIT_REGEXP= "\\s+";

public static String breakLines(String input, int maxLineLength) {
    String[] tokens = input.split(SPLIT_REGEXP);
    StringBuilder output = new StringBuilder(input.length());
    int lineLen = 0;
    for (int i = 0; i < tokens.length; i++) {
        String Word = tokens[i];

        if (lineLen + (SPACE_SEPARATOR + Word).length() > maxLineLength) {
            if (i > 0) {
                output.append(NEWLINE);
            }
            lineLen = 0;
        }
        if (i < tokens.length - 1 && (lineLen + (Word + SPACE_SEPARATOR).length() + tokens[i + 1].length() <=
                maxLineLength)) {
            Word += SPACE_SEPARATOR;
        }
        output.append(Word);
        lineLen += Word.length();
    }
    return output.toString();
}

System.out.println(breakLines("THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A     LEGAL AND BINDING " +
                "AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing     your use of this site, " +
            "www.nationalgeographic.com, which includes but is not limited to products, " +
            "software and services offered by way of the website such as the Video Player.", 20));

Les sorties :

THESE TERMS AND
CONDITIONS OF
SERVICE (the Terms)
ARE A LEGAL AND
BINDING AGREEMENT
BETWEEN YOU AND
NATIONAL GEOGRAPHIC
governing your use
of this site,
www.nationalgeographic.com,
which includes but
is not limited to
products, software
and services 
offered by way of
the website such as
the Video Player.
4
Saad Benbouzid

J'ai récemment écrit quelques méthodes pour ce faire qui, si aucun caractère d'espacement n'est présent dans l'une des lignes, opte pour le fractionnement sur d'autres caractères non alphanumériques avant de recourir à un fractionnement au milieu de Word.

Voici comment cela s'est avéré pour moi:

(Utilise les méthodes lastIndexOfRegex() que j'ai publiées ici .)

/**
 * Indicates that a String search operation yielded no results.
 */
public static final int NOT_FOUND = -1;



/**
 * Version of lastIndexOf that uses regular expressions for searching.
 * By Tomer Godinger.
 * 
 * @param str String in which to search for the pattern.
 * @param toFind Pattern to locate.
 * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
 */
public static int lastIndexOfRegex(String str, String toFind)
{
    Pattern pattern = Pattern.compile(toFind);
    Matcher matcher = pattern.matcher(str);

    // Default to the NOT_FOUND constant
    int lastIndex = NOT_FOUND;

    // Search for the given pattern
    while (matcher.find())
    {
        lastIndex = matcher.start();
    }

    return lastIndex;
}

/**
 * Finds the last index of the given regular expression pattern in the given string,
 * starting from the given index (and conceptually going backwards).
 * By Tomer Godinger.
 * 
 * @param str String in which to search for the pattern.
 * @param toFind Pattern to locate.
 * @param fromIndex Maximum allowed index.
 * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
 */
public static int lastIndexOfRegex(String str, String toFind, int fromIndex)
{
    // Limit the search by searching on a suitable substring
    return lastIndexOfRegex(str.substring(0, fromIndex), toFind);
}

/**
 * Breaks the given string into lines as best possible, each of which no longer than
 * <code>maxLength</code> characters.
 * By Tomer Godinger.
 * 
 * @param str The string to break into lines.
 * @param maxLength Maximum length of each line.
 * @param newLineString The string to use for line breaking.
 * @return The resulting multi-line string.
 */
public static String breakStringToLines(String str, int maxLength, String newLineString)
{
    StringBuilder result = new StringBuilder();
    while (str.length() > maxLength)
    {
        // Attempt to break on whitespace first,
        int breakingIndex = lastIndexOfRegex(str, "\\s", maxLength);

        // Then on other non-alphanumeric characters,
        if (breakingIndex == NOT_FOUND) breakingIndex = lastIndexOfRegex(str, "[^a-zA-Z0-9]", maxLength);

        // And if all else fails, break in the middle of the Word
        if (breakingIndex == NOT_FOUND) breakingIndex = maxLength;

        // Append each prepared line to the builder
        result.append(str.substring(0, breakingIndex + 1));
        result.append(newLineString);

        // And start the next line
        str = str.substring(breakingIndex + 1);
    }

    // Check if there are any residual characters left
    if (str.length() > 0)
    {
        result.append(str);
    }

    // Return the resulting string
    return result.toString();
}
1
Tomer Godinger

Ma version (la précédente ne fonctionnait pas)

public static List<String> breakSentenceSmart(String text, int maxWidth) {

    StringTokenizer stringTokenizer = new StringTokenizer(text, " ");
    List<String> lines = new ArrayList<String>();
    StringBuilder currLine = new StringBuilder();
    while (stringTokenizer.hasMoreTokens()) {
        String Word = stringTokenizer.nextToken();

        boolean wordPut=false;
        while (!wordPut) {
            if(currLine.length()+Word.length()==maxWidth) { //exactly fits -> dont add the space
                currLine.append(Word);
                wordPut=true;
            }
            else if(currLine.length()+Word.length()<=maxWidth) { //whole Word can be put
                if(stringTokenizer.hasMoreTokens()) {
                    currLine.append(Word + " ");
                }else{
                    currLine.append(Word);
                }
                wordPut=true;
            }else{
                if(Word.length()>maxWidth) {
                    int lineLengthLeft = maxWidth - currLine.length();
                    String firstWordPart = Word.substring(0, lineLengthLeft);
                    currLine.append(firstWordPart);
                    //lines.add(currLine.toString());
                    Word = Word.substring(lineLengthLeft);
                    //currLine = new StringBuilder();
                }
                lines.add(currLine.toString());
                currLine = new StringBuilder();
            }

        }
        //
    }
    if(currLine.length()>0) { //add whats left
        lines.add(currLine.toString());
    }
    return lines;
}
1
repo

Depuis Java 8 , vous pouvez également utiliser Streams pour résoudre ces problèmes.

Vous trouverez ci-dessous un exemple complet qui utilise réduction à l'aide de la méthode .collect ()

Je pense que celle-ci devrait être plus courte que les autres solutions non tierces.

private static String multiLine(String longString, String splitter, int maxLength) {
    return Arrays.stream(longString.split(splitter))
            .collect(
                ArrayList<String>::new,     
                (l, s) -> {
                    Function<ArrayList<String>, Integer> id = list -> list.size() - 1;
                    if(l.size() == 0 || (l.get(id.apply(l)).length() != 0 && l.get(id.apply(l)).length() + s.length() >= maxLength)) l.add("");
                    l.set(id.apply(l), l.get(id.apply(l)) + (l.get(id.apply(l)).length() == 0 ? "" : splitter) + s);
                },
                (l1, l2) -> l1.addAll(l2))
            .stream().reduce((s1, s2) -> s1 + "\n" + s2).get();
}

public static void main(String[] args) {
    String longString = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011.";
    String SPLITTER = " ";
    int MAX_LENGTH = 20;
    System.out.println(multiLine(longString, SPLITTER, MAX_LENGTH));
}
1
Markus Weninger