【问题标题】:Extract substring in C在C中提取子字符串
【发布时间】:2018-09-28 22:46:07
【问题描述】:

我正在尝试用 C 语言编写一个方法,该方法将提取起始字符串和结束字符串之间的子字符串。基于布尔标志,它可能包含/排除起始子字符串。 即,

 char source[100] = "Some random text with $$KEY:value$$";
 char dest[12];
 extractSubstring (source, dest, "KEY:", "$", false);

这应该填充 dest = "value"。

我的程序如下:

#include <stdio.h>
typedef int bool;
#define true 1
#define false 0

int main()
{
    char source[100] = "Some random text with $$KEY:value$$";
    char dest[12];
    extractSubstring (source, dest, "KEY:", "$", false);
    return 0;
}

void extractSubstring (char *source, char *dest, char *startingText,
          char *endingText, bool includeStart)
{
    int sourceLen = strlen(source);
    int startLen = strlen(startingText);
    int endingIndex = sourceLen;
    source = strstr (source, startingText);
    if(includeStart){
        strcpy (dest, source);
    }
    else{
       source+=startLen;
       strcpy (dest, source);
    }
    if(strlen(endingText)>0){
        int endingIndex = strstr (dest, endingText) - dest;

    }
    dest[endingIndex] = '\0';
    printf(dest);
}

这会将 dest 填充为“value$$”而不是“value”。如何丢弃最后一个字符。

【问题讨论】:

  • int endingIndex = strstr (dest, endingText) - dest; 隐藏变量。dest[endingIndex] = '\0'; 之后可以写入越界。
  • 多么愚蠢的错误。谢谢

标签: c arrays string substring


【解决方案1】:

问题来自变量的生命周期(此处为endingIndex)。删除 int 应该可以解决问题,但我建议不要将不必要的字符写入 dest(有溢出的风险)。
(另外,对于数组长度,您应该使用 size_t 类型。)

您应该以这种方式优化字符串的编写方式:

void extractSubstring (char *source, char *dest, char *startingText,
          char *endingText, bool includeStart)
{
    size_t sourceLen = strlen(source);
    size_t startLen = strlen(startingText);
    size_t endingIndex = sourceLen;
    source = strstr (source, startingText);
    if(!includeStart){
       source+=startLen;
    }

    if(strlen(endingText)>0){
        endingIndex = strstr (source, endingText) - source;
        strncpy(dest, source, endingIndex);
    } else {
        strcpy (dest, source);
    }

    dest[endingIndex] = '\0';
    printf(dest);
}

希望对你有帮助。

[编辑:wildplasser 评论解释得很好]

【讨论】:

  • source = strstr (source, startingText); if(!includeStart){ source+=startLen; } ... strstr (source, endingText) - source; 看起来很可疑,因为当再次使用 source 时,source 可能是 NULL。
  • source 可能是 NULL,如果它最初是 NULL,或者如果 startingText 等于 source。我猜应该是函数的前提。还是我错过了什么?
  • 如果找不到模式,source = strstr (source, startingText); 缺少路径。代码将受益于char *f = strstr (source, startingText); if (f) do_this(f) else do_that;
猜你喜欢
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
相关资源
最近更新 更多