Break line after a number of characters without cutting the word

Asked

Viewed 747 times

1

I’m trying to solve a little java dojo:

Write a program in which given a sentence and the amount of columns that can be displayed on the screen, break lines without breaking the words. For example, if we pass the phrase "A small, nosy Jabuti saw ten happy storks." and ask for it to be displayed in 20 columns, we will have as a response:

Um pequeno jabuti
xereta viu dez
cegonhas felizes.

But in my code he’s breaking the word after the 20 character.

public static void main(String[] args) {
        String texto = "Um pequeno jabuti xereta viu dez cegonhas felizes.";
        String novoTexto = "";
        int contadorQntLetras = 0;
        int limiteLinha = 20;

        for( int i = 0; i < texto.length(); i++ ) {
            novoTexto += texto.charAt(i);
            contadorQntLetras++;

            if( contadorQntLetras >= limiteLinha) {
                contadorQntLetras = 0;
                novoTexto += "\n";
            }
        }

        System.out.println(novoTexto);
    }

Upshot:

Um pequeno jabuti xe
reta viu dez cegonha
s felizes.

1 answer

1

The problem is that you are only counting the letters, disregarding the concept of words.

In this case, an option is to divide the input text by spaces, generating an array of words. Then iterate over the word array to rebuild the text, remembering to put the line break check before concatenating a word:

public static void main(String[] args) {
  String texto = "Um pequeno jabuti xereta viu dez cegonhas felizes.";
  StringBuilder novoTexto = new StringBuilder();

  String[] palavras = texto.split(" ");

  int contadorQntLetras = 0;
  int limiteLinha = 20;

  for (String palavra : palavras) {

    if(contadorQntLetras + palavra.length() >= limiteLinha) {
      contadorQntLetras = 0;
      novoTexto.append('\n');
    }

    novoTexto.append(palavra);
    novoTexto.append(' ');
    contadorQntLetras += palavra.length() + 1;
  }
  System.out.println("Result");
  System.out.println(novoTexto);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.