Eldon Hipolito
Eldon Hipolito

Reputation: 724

Is it possible to display strings with new line inline

I have 2 strings

String str1 = "FIRST \n SECOND" 
String str2 = "FIRST \n SECOND"

Is it possible for it to be displayed like this?

FIRST         FIRST
SECOND   SECOND

Upvotes: 0

Views: 139

Answers (2)

npinti
npinti

Reputation: 52185

I do not think that you can do that with simple print statements.

What you can try, on the other hand, would be to have a list of string builders, one for each line. You would then split the string by \n and you place each item in the array in the next string builder.

Once that you would have finished, you would then simply need to traverse the list of string builders and print the content.

So basically (untested code, should give you an idea of what needs doing though):

List<StringBuilders> list = new ArrayList<>();
String str = '...';
String[] parsedLine = str.split("\\n");
for(int i = 0; i < parsedLine.length;i++) {
    if(list.size() <= i) list.add(new StringBuilder());

    list.get(i).append(parsedLine + "\t");
}

for(StringBuilder sb : list) {
    System.out.println(sb.toString());
}

Upvotes: 1

Sanjit Kumar Mishra
Sanjit Kumar Mishra

Reputation: 1209

You May use first split and rejoin it using white space. it will work sure.

String finalString = "";    
String[] finalStringArray = inputString.split("[\\n]+");
for(int i = 0; i<finalStringArray.lengh; i++){
   finalString = finalString+" "+finalStringArray[i];  
}

Upvotes: 0

Related Questions