c - 在C中提取字符串(子字符串)的某个部分
问题描述
我正在尝试从使用语言 C 存储为 char 数组的字符串中提取商店的名称。每个都包含商品的价格及其所在的商店。我有许多遵循这种格式的字符串,但我在下面提供了几个示例:
199 at Amazon
139 at L.L.Bean
379.99 at Best Buy
345 at Nordstrom
如何从这些字符串中提取商店的名称?先感谢您。
解决方案
const char *sought = "at ";
char *pos = strstr(str, sought);
if(pos != NULL)
{
pos += strlen(sought);
// pos now points to the part of the string after "at";
}
else
{
// sought was not find in str
}
如果要在 之后提取一部分pos
,而不是整个剩余字符串,可以使用memcpy
:
const char *sought = "o ";
char *str = "You have the right to remain silent";
char *pos = strstr(str, sought);
if(pos != NULL)
{
char word[7];
pos += strlen(sought);
memcpy(word, pos, 6);
word[6] = '\0';
// word now contains "remain\0"
}
推荐阅读
- python - 通过索引和掩码更新?
- variables - 在 terraform.tfvars 中声明列表和映射变量值
- r - 从 r 中的变量选项创建带有 1 和 0 的变量
- sql - 访问外键记录的问题
- algebra - 有多少种不同类型的代数?我的意思是布尔、关系、谓词、模糊代数等
- webpack - 为什么在使用 webpack/babel 转译 jsx 时会得到一英里长的输出文件?
- ssl - HTTPS 欺骗以支持旧版应用程序
- javascript - OpenLayers 不会自动刷新地图上的图标
- flutter - 颤动缓存网页中的webview吗?
- azure - 是否可以与应用程序网关分开配置后端地址池