tags:

views:

429

answers:

6

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.

+2  A: 
HanClinto
Good point -- I'd forgotten about that option to %s
HanClinto
You can use "%.#s", where # is the maximum number of characters to print.
Raymond Martineau
+2  A: 

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.

friol
You would be surprised the number of applications where string constructs are not available. This is particularly the case in the games industry. It is not a bad idea to have an understanding of how strings work as char arrays, especially as it raises all sorts of issues like mem. management etc.
xan
A: 

You could use realloc to reallocate the string buffer (it's not on the stack, is it?) then memmove to shift the necessary characters.

eduffy
A: 

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)
CodeSlave
A: 

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);
efotinis
+2  A: 
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]);
Doug Currie
+1 for a simple, readable solution that is perfectly acceptable given limited scope.
Draemon