c - 如何比较 C 字符串中的子字符串和解析数字

标签 c string

我是低级编程的新手,一直遇到以下问题:

我得到以下格式的字符串:

?cmd=ASET&<hour>&<minute>

其中小时和分钟值始终由 2 个十进制数组成。 所以可以接收的字符串的例子是:

"?cmd=ASET&08&30"

我正在尝试编写一个 if 语句来识别字符串以“?cmd=ASET”开头并将两个名为分钟和小时的全局变量更改为字符串中的值。我一直在尝试使用 strtok() 执行此操作,但到目前为止还没有任何运气。所以我的 if 语句的全局布局是:

if (String starts with "?cmd=ASET") {
   minute = value found in the string;
   hour = value found in the string;
}

如果有任何帮助,我将不胜感激。

最佳答案

尝试这样的操作,其中 cmd 是一个 char * 或 char [] 类型的变量。请注意,strncmp()strcmp() 更安全。通常,在 C 编程中,您希望使用限制长度的函数变体,以避免堆栈溢出攻击和其他安全风险。如果输入错误,字符串到数字函数可能会失败,因此最好使用一种可以检查其状态的表单,这就是为什么 atoi()atol()不推荐。 sscanf() 允许像 strtol() 一样检查状态,因此它们都是可接受的。

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

int
main() 
{
   char *string = "?cmd=ASET&12&30";
   #define ASET_CMD "?cmd=ASET"
   int hour = 0, minute = 0;
   if (strncmp(string, ASET_CMD, strlen(ASET_CMD)) == 0) {
       if (sscanf(string + strlen(ASET_CMD), "&%d&%d", &hour, &minute) != 2)  {
          printf("Couldn't parse input string");
          exit(EXIT_FAILURE);
       }
   }
   printf("hour: %d, minute: %d\n", hour, minute);
   return(EXIT_SUCCESS);
}

$ cc -o prog prog.c
$ ./prog
hour: 12, minute: 30

关于c - 如何比较 C 字符串中的子字符串和解析数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29420564/

相关文章:

c - Structs 的堆和堆栈问题 - C 编程

python - 在 Python 中反转字符串但保留数字的原始顺序

python - 为什么 json.loads 关心使用哪种类型的引号?

c - Linux 内核 : strncpy_from_user() copying too many bytes

java - 为什么 String.strip() 比 String.trim() 在 Java 11 中的空白字符串快 5 倍

c - 如何监控程序调用的cpu指令

c - 直接内存访问的段错误

c - watch 描述符到底是什么? (Linux inotify 子系统)

C11 _通用 : how to deal with string literals?

c - 从输入文件中读取并将单词存储到数组中