简体   繁体   English

C-将子字符串转换为int

[英]C - Convert substring to int

At the moment I got this simple code in C to convert days, minutes and seconds to seconds only: 目前,我用C语言获得了此简单代码,可将天,分钟和秒仅转换为秒:

EDITED (I understood the problem with atoi, like this is corrected right?): 编辑 (我了解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;
}

This is working as I want, but there isn't another way to do it, without creating more variables (like C# where I just need to convert "inline". Does C only have functions that convert to variables and not to "inline")? 这可以按我想要的方式工作,但是没有另一种方法,也可以不创建更多变量(例如C#,我只需要转换“内联”。C是否只有转换为变量而不是“内联”的函数) )?

C# Example: 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));

You can spot the number of lines difference I guess :). 您可以发现行数差异,我猜:)。

You can use atoi() or strtol() to do this job. 您可以使用atoi()strtol()来完成这项工作。 You do not need to extract substrings first, because these functions stop at the first character that cannot be converted. 您不需要首先提取子字符串,因为这些函数会停在无法转换的第一个字符处。 You just need to take a varying view of where the string starts. 您只需要对字符串的起始位置采取不同的看法。 Thus, this code is fairly analogous to your C# example: 因此,此代码与您的C#示例非常相似:

int getseconds(const char * time) {
    return atoi(time) * 3600 + atoi(time + 4) * 60 + atoi(time + 8);
}

Of course it will break on some malformed inputs, but so will the C# (albeit not all the same inputs). 当然,它会在某些格式错误的输入上中断,但是C#也会中断(尽管并非所有相同的输入)。

sscanf() with "%n" to detect the end of scanning is close but does use more variables. 带有"%n" sscanf()可以检测到扫描结束,但是确实使用了更多变量。

int getseconds2(const char * time) {
   int h,m,s;
   int n = 0;
   sscanf(time, "%d h%d m%d s %n", &h,&m, &s, &n);
   if (n == 0 || time[n] != '\0') return -1;  // failure
   return h*3600 + m *60 + s;
}

The "%n" saves the count of characters scanned. "%n"保存已扫描的字符数。 Since is used at the end of the format, testing to see if it is non-zero (the original value) and that time ended at the null character insures the integrity of the scan. 由于是在格式末尾使用的,因此测试以查看其是否为非零(原始值)以及该time以空字符结束是否可以确保扫描的完整性。

@chqrlie suggested a mis-match of C# functionality. @chqrlie建议C#功能不匹配。

   // to match C#
   if (n == 0) return -1;  // failure

A much simpler solution is possible: 一个更简单的解决方案是可能的:

int getseconds( const char* time)
{
    int h, m, s = 0 ;
    char sdelim = 0 ;
    int check = sscanf( time, "%dh %dm %d%c", &h, &m, &s, &sdelim ) ;
    if( check == 3 && sdelim = 's' )
    {
        s = ((h * 60) + m) * 60 + s ;
    }

    return s ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM