首页 > 解决方案 > 在C中提取字符串(子字符串)的某个部分

问题描述

我正在尝试从使用语言 C 存储为 char 数组的字符串中提取商店的名称。每个都包含商品的价格及其所在的商店。我有许多遵循这种格式的字符串,但我在下面提供了几个示例:

199 at Amazon
139 at L.L.Bean
379.99 at Best Buy
345 at Nordstrom

如何从这些字符串中提取商店的名称?先感谢您。

标签: csubstringextractc-stringsfunction-definition

解决方案


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"
}

推荐阅读