Home > Software design >  Java How to limit the amount of characters printed in a line
Java How to limit the amount of characters printed in a line

Time:11-17

I’m looking for what I think is a very simple bit of code but I’m struggling to figure it out so let me try and explain as clearly as I can

Basically, I have a string let’s say for example string Tweet =(“Happy Birthday”)

And I have int called width which let’s just say is equal to 3

How would I make it so the string prints only the amount of characters that squeal to the int width per line so it would look like this

Hap
Py 
Bir
Thd
Ay

Sorry again for the poor formatting I don’t know how better to explain it

CodePudding user response:

public static void printLimit(String str, int lineLength) {
    for (int i = 0; i < str.length(); i  ) {
        System.out.print(str.charAt(i));

        if ((i   1) % lineLength == 0)
            System.out.println();
    }
}

CodePudding user response:

As this task actually is hideous in java because of Unicode, here a limited Unicode solution:

  • chars are UTF-16, sometimes a "surrogate" pair of two chars is needed for one Unicode symbol (code point). Putting a newline string in the middle is wrong.
  • é can be one composed letter-e-with-accent or two: a letter-e and a combining diacritical mark for the accent (a zero width accent). I have used the java.text.Normalizer to compose it, NFC. Not NFKCwhich would also compose ligatures like in ff, fiand ffi.
  • Not done: newline characters in the string, invisible characters, like a Right-To-Left control character.

So:

public static void printLinesWrapped(String text, int maxLineLength) {
    text = Normalizer.normalize(text, Normalizer.Form.NFC);
    AtomicInteger lineLength = new AtomicInteger();
    StringBuilder sb = new StringBuilder(maxLineLength * 2);
    text.codePoints()
        .forEach(cp -> {
            sb.appendCodePoint(cp);
            if (lineLength.incremeentAndGet() >= maxLineLength) {
                System.out.println(sb);
                sb.setLength(0);
                lineLength.set(0);
            }
        };
    if (sb.length() != 0) {
        System.out.println(sb);
    }
}

CodePudding user response:

This is a simple version for beginner:

String tweet = null;
int limit = 3;
while(tweet != null && tweet.length() > 0 && tweet.length() > limit) {
    System.out.println(tweet.substring(0, limit));
    tweet = tweet.substring(limit);
}
if(tweet != null && tweet.length() != 0) {
    System.out.println(tweet);
}
else {
    System.out.println("tweet cannot be null");
}
  • Related