Last active
June 1, 2023 07:42
-
-
Save kenresoft/bc91291c6d1d06826002939c38f5498a to your computer and use it in GitHub Desktop.
Payment card number division with a space as the separator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int divisions(String input) { | |
| int divisions = 0; | |
| for (var j = 3; j <= 4; ++j) { | |
| //divisions = 2; | |
| if (input.length % j == 0) { | |
| return divisions = j; | |
| } | |
| } | |
| return divisions; | |
| } | |
| String space(String input) { | |
| int count = 0; | |
| String spacedOutput = ''; | |
| for (var i = 0; i < input.length; i++) { | |
| if (count == divisions(input)) { | |
| spacedOutput += ' '; | |
| count = 0; | |
| } | |
| spacedOutput += input[i]; | |
| count += 1; | |
| } | |
| return spacedOutput.trim(); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
card_number_separator.
The
divisionsfunction takes a string as input and returns the number of divisions the string can be split intoequally. The
spacefunction takes a string as input, adds spaces to the string to make it divisible by the number of divisions returned by thedivisionsfunction, and returns the spaced string.Explanation.
The divisions function.
The
divisionsfunction takes a string as input and returns the number of divisions the string can be split intoequally. It initializes a
divisionsvariable to 0. It then loops through the numbers 3 and 4, and checks if thelength of the input string is divisible by the current number. If it is, the function returns the current number.
If none of the numbers result in a division, the function returns 0.
The space function.
The
spacefunction takes a string as input, adds spaces to the string to make it divisible by the number ofdivisions returned by the
divisionsfunction, and returns the spaced string. It initializes acountvariableto 0 and a
spacedOutputvariable to an empty string. It then loops through the characters of the input string.For each character, it checks if the count variable is equal to the number of divisions returned by the
divisionsfunction. If it is, a space is added to thespacedOutputvariable, and thecountvariable is resetto 0. The current character is then added to the
spacedOutputvariable, and thecountvariable is incrementedby 1. Finally, the function returns the
spacedOutputvariable with leading and trailing spaces removed.