[英]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.