gpt4 book ai didi

c - 如何在分隔符处将 char* 拆分为 3 个 char*?

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:22 25 4
gpt4 key购买 nike

我想将 char* time = "15:18:13"; 拆分为 char* hour;, char* minute;char* seconds;

问题是我不知道怎么做。我想试试 Pebble Watchface。我已经使用了 char* hour = strok(time, ":"); 但第一个参数需要是 char[] 但时间是 char*

有人知道怎么做吗?

最佳答案

根据 alk 的评论,可以使用的方法是 sscanf,如下所示:

#include <string.h>

int main ()
{
char* str = "15:18:13";
int a, b, c;
sscanf(str, "%d:%d:%d", &a, &b, &c);
printf("%d %d %d\n", a, b, c);
return 0;
}

不过,下面是一个更通用的解决方案。

使用strtok。您可以将它们存储在数组中,如下所示:

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

int main ()
{
char str[] ="15:18:13";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,":");
char* a[3];
int i = 0;
while (pch != NULL)
{
a[i] = malloc( (strlen(pch)+1) * sizeof(char));
strcpy(a[i++], pch);
printf ("%s\n",pch);
pch = strtok (NULL, ":");
}

for(i = 0 ; i < 3 ; i++)
printf ("%s\n",a[i]);

return 0;
}

strdup,正如 Deduplicator 所建议的,也可以提供帮助,但它不是标准的,因此我建议避免(或实现你自己的,并不难)。 :)

此外,Deduplicator提到的strtok_s在C中没有提供。

在下方回复OP的评论:

问题:str 是 char str[] 但 time 是 char*。我可以转换吗?

你可以像这样将它分配给一个数组:

#include <stdio.h>

int main ()
{
char* from = "15:18:13";
char to[strlen(from) + 1]; // do not forget +1 for the null character!
strcpy(to, from);
printf("%s\n", to);
return 0;
}

GIFT:我建议您阅读 here 的第一个答案。 .

它为char*char[] 提供了流畅的解释。

关于c - 如何在分隔符处将 char* 拆分为 3 个 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23408641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com