如何从c中的日期时间字符串中删除空格

art*_*sol 1 c string

下面的代码创建一个包含日期和时间的字符串 Wed Jul 26 14:45:28 2017

我怎么能从中删除空格?那就是WedJul2614:45:28

原始代码:

#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);
}
Run Code Online (Sandbox Code Playgroud)

我尝试了这个代码,但它打印出来 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);  
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 6

int j = 0;
for (int i = 0; s[i]!='\0'; i++) {
  if (s[i] != ' ') {
    temp[j] = s[i];
    j++;
  }
}
Run Code Online (Sandbox Code Playgroud)

跟踪索引,这样您就不会只留下一些随机值的空格.此外,您应该在temp的末尾添加一个null.

temp[j] = '\0';
Run Code Online (Sandbox Code Playgroud)