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 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
card_number_separator.
The
divisions
function takes a string as input and returns the number of divisions the string can be split intoequally. The
space
function takes a string as input, adds spaces to the string to make it divisible by the number of divisions returned by thedivisions
function, and returns the spaced string.Explanation.
The divisions function.
The
divisions
function takes a string as input and returns the number of divisions the string can be split intoequally. It initializes a
divisions
variable 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
space
function takes a string as input, adds spaces to the string to make it divisible by the number ofdivisions returned by the
divisions
function, and returns the spaced string. It initializes acount
variableto 0 and a
spacedOutput
variable 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
divisions
function. If it is, a space is added to thespacedOutput
variable, and thecount
variable is resetto 0. The current character is then added to the
spacedOutput
variable, and thecount
variable is incrementedby 1. Finally, the function returns the
spacedOutput
variable with leading and trailing spaces removed.