-2

Let's say I have a string:

String pers = "PROCESS / PROGRAM / PROJECT / SERVICE DELIVERY";

How do I break line when the string's length reaches 30? So it will result in:

PROCESS / PROGRAM / PROJECT /

SERVICE DELIVERY

My attempt:

String pers = "PROCESS / PROGRAM / PROJECT / SERVICE DELIVERY";
if (pers.length() > 30) {
  pers = pers.substring(0, 30) + "\n" + pers.substring(30, pers.length());
}

It returns Uncaught SyntaxError: Invalid or unexpected token at the browser's console. Please help.

Brian Cheong
  • 61
  • 3
  • 12

3 Answers3

1

You could use something like so:

String pers = "PROCESS / PROGRAM / PROJECT / SERVICE DELIVERY";
String formattedString = pers.replaceAll("(.{30})", "$1\n");

The above should replace 30 characters with whatever is matched plus a new line character.

npinti
  • 51,780
  • 5
  • 72
  • 96
0

A StringBuilder would probably be an easier way to work with string manipulation. You can try this also using String Builder.

String s = "A very long string containing " +
    "many many words and characters. " +
    "Newlines will be entered at spaces.";

StringBuilder sb = new StringBuilder(s);

int i = 0;
while ((i = sb.indexOf(" ", i + 30)) != -1) {
    sb.replace(i, i + 1, "\n");
}

System.out.println(sb.toString());

If you know about Regular Expressions then this is the best and easiest way:-

String str = "....";
String parsedStr = str.replaceAll("(.{30})", "$1\n");

This will replace every 30 characters with the same 30 characters and add a new line at the end.

Ravindra Kumar
  • 1,842
  • 14
  • 23
0

Try this one:

public ArrayList gecStringFromStringByNumberOfChars(String str, int numberOfChars) {

int numberOfLine = str.length() / numberOfChars;
int offsets = str.length() % numberOfChars;
ArrayList<String> result = new ArrayList<>();
for (int i = 0; i < numberOfLine; i++) {
    result.add(str.substring(i * numberOfChars, i * numberOfChars + numberOfChars));
}
if (offsets > 0) {
    result.add(str.substring(str.length() - offsets, str.length()));
}
return result;
}

in code call it gecStringFromStringByNumberOfChars(pers,30)

DeadCoon
  • 81
  • 4