如何在Java中实现信用卡号每4位加空格的toString方法?
toString() Method for CreditCardNumber with 4-Character Spacing Got it, let's tackle this toString() implementation. The goal is to combine the issuer ID, account number, and check digit into a single string with a space every 4 characters—without modifying any instance variables. Here's a clean, efficient way to do it using StringBuilder:
Step-by-Step Implementation
First, we'll create the full unformatted card number string by concatenating the three fields (making sure to convert the checkDigit int to a string). Then we'll iterate through this string, adding characters to a StringBuilder and inserting spaces at every 4th character (except after the last one).
public String toString() { // Create the full unformatted card number (no changes to instance vars) String fullCard = issuerId + accountNum + String.valueOf(checkDigit); StringBuilder formatted = new StringBuilder(); for (int i = 0; i < fullCard.length(); i++) { // Add the current character to the builder formatted.append(fullCard.charAt(i)); // Add a space after every 4th character, but not at the end if ((i + 1) % 4 == 0 && i != fullCard.length() - 1) { formatted.append(' '); } } return formatted.toString(); }
How This Works
- No Instance Variable Modifications: We're only reading
issuerId,accountNum, andcheckDigitto create a new string—never altering the original fields. - Spacing Logic: Since we start counting from 0,
i + 1gives us the 1-based position of the current character. When this position is a multiple of 4, and we're not at the last character, we insert a space. This ensures we don't get an extra trailing space at the end of the string. - Compatibility: Even if the total length wasn't a perfect multiple of 4 (though in your case it's 16, which splits neatly into 4 groups of 4), this code still works—it just won't add a space after the final partial group.
Example Output
If your issuerId is "123456", accountNum is "789012345", and checkDigit is 9, the output will be:
1234 5678 9012 3459
内容的提问来源于stack exchange,提问作者raska09

