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

标签 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);
}

我试过这段代码,但它打印出 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++;
  }
}

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

temp[j] = '\0';

关于c - 如何从c中的日期时间字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329017/

相关文章:

c - 从C中的长字符串中读取字符串

javascript - 如何为 javascript 删除字符串

c - 当用户输入超出使用 fgets 所需的范围时该怎么办?

.NET字符串串联(+&+ =)与StringBuilder

split函数调用中的Java正则表达式表达式问题

c - 在 C 中寻找一个好的哈希表实现

c - 打开旧版本的 C 文件

c - 不太确定怎么了

c - AVR 中断的变量在 main 中更新

c - FreeBSD kldload : can't load, 没有这样的文件或目录