Skip to content

Instantly share code, notes, and snippets.

@kenresoft
Last active June 1, 2023 07:42
Show Gist options
  • Save kenresoft/bc91291c6d1d06826002939c38f5498a to your computer and use it in GitHub Desktop.
Save kenresoft/bc91291c6d1d06826002939c38f5498a to your computer and use it in GitHub Desktop.
Payment card number division with a space as the separator.
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();
}
@kenresoft
Copy link
Author

card_number_separator.

The divisions function takes a string as input and returns the number of divisions the string can be split into
equally. The space function takes a string as input, adds spaces to the string to make it divisible by the number of divisions returned by the divisions 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 into
equally. It initializes a divisions variable to 0. It then loops through the numbers 3 and 4, and checks if the
length 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 of
divisions returned by the divisions function, and returns the spaced string. It initializes a count variable
to 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 the spacedOutput variable, and the count variable is reset
to 0. The current character is then added to the spacedOutput variable, and the count variable is incremented
by 1. Finally, the function returns the spacedOutput variable with leading and trailing spaces removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment