首页 > 解决方案 > sscanf 获取字符串直到第二个符号(包括一个)

问题描述

如何通过sscanf获取字符串直到第二个符号?

例如:

char *str = "struct1.struct2.struct3.int";
char buf[256] = {0};
sscanf(str, "", buf); //have any format string could get string until second dot?

标签: c

解决方案


sscanf 获取字符串直到第二个符号(包括一个)
如何通过 sscanf 获取字符串直到第二个符号?

单次使用通常是不可能的sscanf()

当然,如果没有大量工作,更复杂的使用sscanf()将适用于许多输入字符串,但对于选择的字符串1会失败。 sscanf()不是最适合此任务的。

strchr(), strcspn()更适合。

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

// Return offset to 2nd needle occurrence
// or end of string, if not found.   
size_t foo(const char *haystack, const char *needle) {
  size_t offset = strcspn(haystack, needle);
  if (haystack[offset]) {
    offset++;
    offset += strcspn(haystack + offset, needle);
  }
  return offset;
}

#include <stdio.h>
int main() {
  const char *haystack = "struct1.struct2.struct3.int";
  printf("<%.*s>\n", (int) foo(haystack, "."), haystack);
}

输出

<struct1.struct2>

1考虑:"struct1.struct2", "struct1..", "..struct2", ".struct2.", "..", ".", "".


推荐阅读