Nejc Osterman
Nejc Osterman

Reputation: 51

How do you limit characters in each line in java?

I am wondering how can I limit characters in each line. If the next word is too long to fit in a - example 12 character line, so it goes in next line.

import java.io.File;
import java.util.Scanner;

public class Programme {
    public static void main(String[] args)throws Exception {
        method1(args[0],args[1]);

    }
    public static void method1(String file, String n)throws 
Exception{
        Scanner sc = new Scanner(new File(file));
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String [] splitv = line.split(" ");
            char[] splitv2 = line.toCharArray();
            for (int i=0;i<Integer.parseInt(n);i++){
                System.out.print(splitv2[i]);
            }
            System.out.println("");
        }
    }    
}

This is an unfinished programme, I want it to work if for example it gets a text file with text below and second argument "n" as 12:

01 23 456 789 012 3 4 
56 78 9 0 12 34 56 789

The programme output would be:

01 23 456
789 012 3 4
56 78 9 0 12
34 56 789

Space is also a character that counts and 789 in this case would not fit in to be a 12 character line, so it is printed in the next line.

Upvotes: 0

Views: 1133

Answers (1)

Andreas
Andreas

Reputation: 159260

Concatenate your input into a single string, then use lastIndexOf(' ', 12) to find the space to break on.

String input = "01 23 456 789 012 3 4 56 78 9 0 12 34 56 789";
while (input.length() > 12) {
    int idx = input.lastIndexOf(' ', 12);
    System.out.println(input.substring(0, idx));
    input = input.substring(idx + 1);
}
System.out.println(input);

Output

01 23 456
789 012 3 4
56 78 9 0 12
34 56 789

If the text can contain long words, you need extra logic to guard against them.

String input = "123456789012345 6 789012345678901 234 567 8 9 01 23 4 5 67 89 01 234567890123456";
while (input.length() > 12) {
    int idx = input.lastIndexOf(' ', 12);
    if (idx == -1) { // too long word
        idx = input.indexOf(' ', 12);
        if (idx == -1) // last word
            break;
    }
    System.out.println(input.substring(0, idx));
    input = input.substring(idx + 1);
}
System.out.println(input);

Output

123456789012345
6
789012345678901
234 567 8 9
01 23 4 5 67
89 01
234567890123456

If the text can contain consecutive spaces, you should eliminate them first.

input = input.replaceAll("\\s+", " ").trim();

Upvotes: 3

Related Questions