Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting strings in java

Tags:

java

string

I am reading the serial buffer with readLine() method. The string returned by readLine() is in the format "str1 : str2". In a while loop when I use readLine() number of times for a response of serial port command I get weird output like this :

String1 : string1
SString11 : String2
StringString2 : String23 
String4 : String5

But I need the output formatted as below

String1       : string1
SString11     : String2
StringString2 : String23 
String4       : String5

I used the split method on string and get the two strings separated with delimiter as ':'. But now I need to append the String1 with spaces to align all the colons.

I am sorry If my problem explanation is weird. But If anybody understood the problem can you please suggest how to do it?

like image 929
Surjya Narayana Padhi Avatar asked Dec 14 '09 05:12

Surjya Narayana Padhi


2 Answers

The easiest way to achieve this is to use System.out.format(). This lets you use C printf style format specifiers. An example:

System.out.format("%-5s:%10s\n", "Name", "Nemo");
System.out.format("%-5s:%10d\n", "Age", 120);

This will output:

Name :      Nemo
Age  :       120

Also see documentation for the Formatter class to learn more about the format string syntax.

like image 198
Vijay Mathew Avatar answered Nov 09 '22 17:11

Vijay Mathew


Take a look at System.out.printf

like image 6
TofuBeer Avatar answered Nov 09 '22 18:11

TofuBeer