[英]How to remove spaces from date time string in c
下面的代码创建一个带有日期和时间的字符串,例如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';
马特的答案有效,但您也可以这样做:
该示例无需调用系统功能:strlen。 在这里我们不需要它。 有点优化。
i = 0;
int j = 0;
while (s[i] != '\0')
{
if (s[i] == ' ')
{
temp[j] = s[i];
j++;
}
i++;
}
temp[j] = '\0';
不要忘记字符串末尾的“ \\ 0”。
马特已经为您的要求提供了答案。
您可能想要或需要的也可以轻松实现。 如果您不想要空格,只需避免首先添加空格:
用直接创建所需内容的字符串替换strftime()
的格式字符串"%c"
,该字符串为您的语言环境提供标准格式: "%a%b%d%T"
稍微贵一点,但是您至少不需要另一个变量,并且每次修改都具有有效的字符串。
#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);
}
}
您可以使用标准库函数将空间压缩到位。 鉴于字符串非常短且只有几个空格,因此性能不会受到太大影响。
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.