c - 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?
解决方案
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."
, ".."
, "."
, ""
.
推荐阅读
- xml - 找不到对象方法 setData - 在 XML 文件中保存值
- python - 如何从 pandas DataFrame 制作字典列表?
- javascript - 如何使用带有 django 布尔字段的切换开关?
- java - 查找 Android 应用程序中 y 占 x 的百分比
- python-3.x - 无法使用 UNet 训练图像分割模型
- asp.net-core - 是否可以将 .Net Core 配置为使用文件系统来缓存响应?
- c - 在动画期间在OpenGL中获取鼠标点击坐标?
- javascript - 反应:当活动不起作用时更改按钮颜色
- verilog - 如何在 FPGA 的 Verilog 中找到 2 个脉冲之间的中间点?
- jquery - jQuery 表单更改检测异常