Reputation: 125
I have a simple cardNumber String that I'm trying to Format for my System.out.ln
Here is the method that my System.out.ln calls
public String getCardNumber()
{
cardNumber = "0000 0000 0000 0000";
return cardNumber;
}
but the made up part of cardNumber = "0000 0000 0000 0000"; is what I'm trying to format it like, so 12345678912345752 becomes 1234 5678 9124 5752
I've had a look at substring() and stuff but I can't see a simple way to go through every 4 characters and insert a space automatically.
Upvotes: 0
Views: 5281
Reputation:
try out the following method:
public String getNumberString() {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat fmt = new DecimalFormat("0000,0000,0000,0000", symbols);
return fmt.format(this.number);
}
Upvotes: 1
Reputation: 923
To add a space after every 4 characters in a 16 character string, do this.
String number = "1234123412341234";
number = number.substring(0,3) + " " + number.substring(4, 7) + " " + number.substring(8, 11) + " " + number.substring(12, number.length());
Upvotes: 2
Reputation: 3358
You just need to manually edit your string
String input = "1234567891245752";
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i % 4 == 0 && i != 0) {
result.append(" ");
}
result.append(input.charAt(i));
}
System.out.println(result.toString());
See what we're doing here is iterating over your string, and adding a whitespace in between every 4 characters.
Upvotes: 8