目前,我用C语言获得了此简单代码,仅将天,分钟和秒转换为秒:
编辑(我了解atoi的问题,这样可以更正吗?):
#include <stdio.h>
#include <stdlib.h>
int getseconds(char * time)
{
int seconds=0, i=0;
char buffer[3];
while (*time != '\0')
{
switch (*time)
{
case 'h': buffer[i]='\0';i=0;seconds=seconds+atoi(buffer)*3600;break;
case 'm': buffer[i]='\0';i=0;seconds=seconds+atoi(buffer)*60;break;
case 's': buffer[i]='\0';i=0;seconds=seconds+atoi(buffer);break;
case ' ':break;
default: buffer[i]=*time;i++;break;
}
time++;
}
return seconds;
}
int main()
{
char *time = "12h 4m 58s";
int seconds = getseconds(time);
printf("%d",seconds);
return 0;
}
这可以按我想要的方式工作,但是没有另一种方法,也可以不创建更多变量(例如C#,我只需要转换“内联”。C是否只有转换为变量而不是“内联”的函数) )?
C#示例:
string time = "12h 34m 58s";
int seconds = int.Parse(time.Substring(0, 2)) * 3600 + int.Parse(time.Substring(4, 2)) * 60 + int.Parse(time.Substring(8, 2));
您可以发现行数差异,我猜:)。
您可以使用atoi()
或strtol()
来完成这项工作。您不需要首先提取子字符串,因为这些函数会停在无法转换的第一个字符处。您只需要对字符串的起始位置采取不同的看法。因此,此代码非常类似于您的C#示例:
int getseconds(const char * time) {
return atoi(time) * 3600 + atoi(time + 4) * 60 + atoi(time + 8);
}
当然,它将在某些格式错误的输入上中断,但是C#也将中断(尽管并非所有相同的输入)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句