Created
April 11, 2017 19:39
-
-
Save dbechrd/611f2e21f700d2ad1e898db650566587 to your computer and use it in GitHub Desktop.
Add commas to string of digits
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
#include <stdio.h> | |
#include <string.h> | |
// Cleanup: This is just for Rodney to see what's happening via printf() | |
void addCommas_debug(const char *num, char *buffer) | |
{ | |
char temp[100] = {0}; | |
int src = strlen(num) - 1; | |
int dst = 0; | |
while (src >= 0) | |
{ | |
temp[dst] = num[src]; | |
printf("temp: %s\n", temp); | |
src--; | |
dst++; | |
if (src < 0) | |
{ | |
break; | |
} | |
if ((src - 1) % 3 == 0) { | |
temp[dst] = ','; | |
dst++; | |
} | |
} | |
printf("temp buffer filled, src: %d dst: %d\n", src, dst); | |
src = dst - 1; | |
dst = 0; | |
printf("reset indices src: %d dst: %d\n", src, dst); | |
while (src >= 0) | |
{ | |
buffer[dst++] = temp[src--]; | |
printf("%s\n", buffer); | |
} | |
} | |
// Inserts commas every third digit of num, result is written to buffer. | |
void addCommas(const char *num, char *buffer) | |
{ | |
char temp[100] = {0}; | |
int src = strlen(num) - 1; | |
int dst = 0; | |
// Copy num into temp from back-to-front. | |
// Add a comma every 3rd digit. | |
while (src >= 0) | |
{ | |
// Copy current char from num to temp | |
temp[dst++] = num[src--]; | |
// End of num, break now to prevent extra comma | |
if (src < 0) | |
break; | |
// Insert comma every third digit | |
if ((src - 1) % 3 == 0) { | |
temp[dst] = ','; | |
dst++; | |
} | |
} | |
// Reuse src and dst indices to reverse-copy temp buffer into final buffer | |
src = dst - 1; | |
dst = 0; | |
while (src >= 0) { | |
buffer[dst++] = temp[src--]; | |
} | |
} | |
int main() | |
{ | |
char num[20] = "12345678"; | |
char buffer[100] = {0}; | |
addCommas_debug(num, buffer); | |
addCommas(num, buffer); | |
printf(" input: %s\n", num); | |
printf("result: %s\n", buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment