Balawi28
Balawi28

Reputation: 179

Date format string simplification

    char* dateFormat(char str[]){
    char temp[11];
    temp[0]=str[0];
    temp[1]=str[1];
    temp[2]='/';
    temp[3]=str[2];
    temp[4]=str[3];
    temp[5]='/';
    temp[6]=str[4];
    temp[7]=str[5];
    temp[8]=str[6];
    temp[9]=str[7];
    temp[10]='\0';

    return temp;
};

This function takes date string (format DDMMYYYY) and returns another string with format (DD/MM/YYYY), is there any way to make a shorter version of it.

Upvotes: 1

Views: 106

Answers (2)

Skizz
Skizz

Reputation: 71060

The only thing I can think of off the top of my head is:-

#include <stdio.h>
#include <string.h>

char *format (char *src)
{
    char temp [11] = {src[0], src[1], '/', src[2], src [3], '/', src [4], src [5], src[6], src[7], 0};
    return strdup (temp);
}

int main()
{
    printf("Hello World %s", format ("12345678"));    
    return 0;
}

Upvotes: 1

Marco Bonelli
Marco Bonelli

Reputation: 69276

First of all, your function is invalid: returning a pointer to a local variable is forbidden in C, and you are doing so by creating a local array and returning its address.

You should either:

  1. Dynamically allocate the needed memory:

    char *dateFormat(char *str) {
        char *res;
    
        res = malloc(11);
        if (res == NULL)
            return NULL;
    
        res[0] = str[0];
        res[1] = str[1];
        res[2] = '/';
        res[3] = str[2];
        res[4] = str[3];
        res[5] = '/';
        res[6] = str[4];
        res[7] = str[5];
        res[8] = str[6];
        res[9] = str[7];
        res[10] ='\0';
    
        return res;
    };
    
  2. Accept a second argument assuming it was already allocated by the caller with enough space:

    void dateFormat(char *src, char *dst) {
        dst[0] = src[0];
        dst[1] = src[1];
        dst[2] = '/';
        dst[3] = src[2];
        dst[4] = src[3];
        dst[5] = '/';
        dst[6] = src[4];
        dst[7] = src[5];
        dst[8] = src[6];
        dst[9] = src[7];
        dst[10] ='\0';
    };
    

Other than this, there is really not much to do to improve your function. Making it any "shorter" doesn't make much sense, as it would most probably also make it slower.

Any function call or loop with branches will inevitably result in slower code. Just compile with optimizations enabled (e.g. gcc -O3 ...) and let the compiler do the magic for you. It will most probably turn those two byte assignments as well as the final four byte assignment into a single move assembly instruction.

Upvotes: 3

Related Questions