【问题标题】:Extracting a Certain portion of a String (Substring) in C在C中提取字符串(子字符串)的某个部分
【发布时间】:2021-05-20 19:57:07
【问题描述】:

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

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

如何从这些字符串中提取商店名称? 提前谢谢你。

【问题讨论】:

  • 使用strstr 找到"at " 的位置,然后完成剩下的。
  • 其他方式:使用strtoksscanf
  • @Stormcaller25 “提取”一词是什么意思?您需要创建一个包含名称的字符数组还是需要获取指向该名称的指针?
  • strcpy(yourbuff, strstr(str,"at") + 3); 假设 str 包含 "at"
  • @VladfromMoscow 我的意思是创建一个包含名称的字符数组。

标签: c substring extract c-strings function-definition


【解决方案1】:

因为它已经在 cmets 中指出,您可以使用标准函数 strstr

这是一个演示程序

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

char * extract_name( const char *record, const char *prefix )
{
    size_t n = 0;
    
    const char *pos = strstr( record, prefix );

    if ( pos )
    {
        pos += strlen( prefix );
        
        while ( isblank( ( unsigned char )*pos ) ) ++pos;
        
        n = strlen( pos );
    }
    
    char *name = malloc( n + 1 );
    
    if ( name )
    {
        if ( pos )
        {
            strcpy( name, pos );
        }
        else
        {
            *name = '\0';
        }
    }
    
    return name;
}

int main(void) 
{
    const char *prefix = "at ";
    
    char *name = extract_name( "199 at Amazon", prefix );
    
    puts( name );
    
    free( name );
    
    name = extract_name( "139 at L.L.Bean", prefix );
    
    puts( name );
    
    free( name );
    
    name = extract_name( "379.99 at Best Buy", prefix );
    
    puts( name );
    
    free( name );
    
    name = extract_name( "345 at Nordstrom", prefix );
    
    puts( name );
    
    free( name );

    return 0;
}

程序输出是

Amazon
L.L.Bean
Best Buy
Nordstrom

函数extract_name 动态创建一个字符数组,用于存储提取的名称。如果内存分配失败,该函数将返回一个空指针。如果未找到名称前的前缀(在本例中为字符串 "at "),则函数返回空字符串。

【讨论】:

    【解决方案2】:
    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"
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 2019-07-08
      • 2018-09-29
      • 2018-08-21
      • 2015-08-01
      • 2013-12-11
      • 2022-11-13
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多