I've a string like "1234567890". Now I need to store/print out this with the following format, 123-456-7890
What is the best method to implement this in C?
Thanks for comments/answers.
I've a string like "1234567890". Now I need to store/print out this with the following format, 123-456-7890
What is the best method to implement this in C?
Thanks for comments/answers.
C, which is a rather "old" language (it belongs to the Seventies), has string manipulation functions, like strcat, strcpy, etc. in its standard library.
Just see the string.h header file reference, it should be enough.
edit: if you can, I suggest you to use a more advanced language like C++, which has much more powerful constructs, like the std::string class. There should be a C++ compiler for almost every OS and platform nowadays, including embedded systems.
You could use realloc to reallocate the string buffer (it's not on the stack, is it?) then memmove to shift the necessary characters.
Without going to far, in case this is homework... What you probably want to use is a combination of strncpy and strcat (along with string.h).
Because of the way strings are handled in C, you will need to reference the start point in the string to start copying from. e.g.,
strncpy (dest, src + startPos, copyLength)
You can copy the characters one by one, while at the same time keeping a counter of the number of characters copied. Before copying a character, check whether the counter is either 3 or 6; if so write a dash ('-') to the output. This will make sure the digits are grouped as needed:
const char* input = "1234567890";
char output[20]; // allocate a buffer big enough to fit the result
const char* src = input; // the current source byte
char* dst = output; // the current destination
int charsCopied = 0; // counter
// loop until we reach the terminating NUL of the source string
while (*src) {
// insert the dash in the output when needed
if (charsCopied == 3 || charsCopied == 6) {
*dst++ = '-';
}
// copy the current character and move to the next
*dst++ = *src++;
charsCopied += 1;
}
// terminate the output string and print it
*dst = '\0';
puts(output);
printf("%c%c%c-%c%c%c-%c%c%c%c"
, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9]);