简体   繁体   中英

How to remove spaces from date time string in c

The code below creates a string with date and time for example Wed Jul 26 14:45:28 2017

How could I remove the spaces from it? So that is is WedJul2614:45:28 ?

Original code:

#include <stdio.h>
#include <time.h>

int main() {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    strftime(s, sizeof(s), "%c", tm);
    printf("%s\n", s);
}

I tried this code but it prints wed?July

#include <stdio.h>
#include <time.h>

int main() {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    char temp[64];
    strftime(s, sizeof(s), "%c", tm);
    printf("%s\n", s);


    for (int i = 0; i < sizeof(s); i++) {
      if (s[i] != ' ') {
        temp[i] = s[i];
      }
    }
printf("%s\n", temp);  
}
int j = 0;
for (int i = 0; s[i]!='\0'; i++) {
  if (s[i] != ' ') {
    temp[j] = s[i];
    j++;
  }
}

Keep track of the index so you don't just leave the spaces with some random value. Also, you should add a null at the end of temp.

temp[j] = '\0';

Matt's answer works but you can do it too:

This exemple is without call to system function: strlen. Here we don't need it. It's a bit optimize.

i = 0;
int j = 0;
while (s[i] != '\0')
  {
    if (s[i] == ' ')
      {
        temp[j] = s[i];
        j++;
      }
    i++;
  }
temp[j] = '\0';

Don't forget the '\\0' at the end of your string.

Matt already provided an answer for what you asked .

What you probably want or need can also be achieved a bit easier. If you don't want spaces, just avoid adding them in the first place:

Replace your format string "%c" for strftime() which provides standard format for your locale with a string that creates directly what you want: "%a%b%d%T"

A bit more expensive, but you at least do not need another variable and as well have a valid string on each modification.

#include <string.h>

...

  size_t l = strlen(s);
  for (size_t i = 0; i < l; ++i) {
    if (s[i] != ' ') {
      memmove(s+i, s+i+1, l-i+1); 
    }
  }

You can squeeze spaces out in place, using standard library functions. Given that the string is very short and there's only a few spaces, performance won't suffer much.

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

int main() {
    time_t t = time(NULL);
    struct tm *tm = localtime(&t);
    char s[64];
    strftime(s, sizeof(s), "%c", tm);
    printf("before: %s\n", s);

    for ( char *p = strchr(s, ' '); p ;  p = strchr(p, ' ') )
        strcpy(p, p+1);

   printf("after: %s\n",s);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM