0

How does one format the following:

From this:

1: My street
2: 1232321
3: Hello there world!
4: A really really really long word!

To this:

1:                           My street
2:                             1232321
3:                  Hello there world!
4:   A really really really long word!

I think it has something to do with String.format() and a bunch of random chars in it!

2
  • 1
    What have you got with String.format()? Commented Dec 1, 2012 at 18:35
  • I think this might be a duplicate or at least very similar question to this. Take a look at that. Commented Dec 1, 2012 at 18:40

1 Answer 1

3

You can first split your string to get 1: and My Street separately, and then format them: -

String str = "1: My street";
String str2 = "3: Hello there world!";

String[] arr = str.split("(?<=:) ");
String[] arr2 = str2.split("(?<=:) ");

System.out.printf("%s%30s\n", arr[0], arr[1]);
System.out.printf("%s%30s", arr2[0], arr2[1]);

Output : -

1:                     My street
3:            Hello there world!

You can do this with String#substring method also, to get the two parts separately.

System.out.printf("%s%30s\n", str.substring(0, 2), str.substring(3));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.