【问题标题】:searching for a substring of a string in c, then making a new string out of it在c中搜索字符串的子字符串,然后从中创建一个新字符串
【发布时间】:2012-03-14 21:06:15
【问题描述】:

C 并不容易。我找遍了,什么也没找到。

我需要在 C 字符串中搜索以“Sample:”开头的子字符串,然后创建一个新的 c 字符串,该字符串由之后的所有字符组成,直到第一个换行符为止。

在 C++ 中,我可以很快做到这一点。有经验的 C 程序员能给我指路吗?

我确信我可以通过手写来做到这一点,但肯定有一些内置函数可以提供帮助吗?

【问题讨论】:

  • 查找 strstr(),也许还有 strchr() 顺便说一句:我可以建议你彻底研究 std 库中的函数。功能不多,但当你需要它们时,你可能会记住它们的名字。
  • 为什么我得到了-1?出于好奇...对我来说似乎是一个合理的问题
  • 可能是因为你抱怨不努力。
  • 不确定应该付出什么努力,因为问题的重点是学习有关使用内置 C 函数的知识,但谢谢。

标签: c string c-strings


【解决方案1】:

strstr()strndup() 是你的朋友,完成后记得释放输出:

const char *input = "Hello Sample: This is a test\nTest";

const char *start = strstr(input, "Sample: ");

if (!start)
{
    // report error here
}

const char *end = strstr(start, "\n");
if (!end)
{
    // you have two options here. 
    // #1: use pure strdup on start and you have your output
    // #2: make this an error, and report it to the user.
}


int length = end - start;

char *output = strndup(start, length);

printf("%s", output); // Prints "Sample: This is a test"

free(output);

如果您知道正确的 API 调用,这并不难。

【讨论】:

  • 我没有意识到你可以减去 char *s。棒极了。这就是我一直在寻找的东西。谢谢。
  • @Aerovistae 它与字符串在内存中的存储方式有关,作为连续的内存块。因此,如果我有一个指向内存索引 a 的指针,那么该指针与内存块的开头之间的差异就是子字符串的长度。
  • @Aerovistae:如果你搜索“指针算法”这个词,你会发现很多解释和例子。
  • 别忘了检查两次调用strstr()的NULL返回并做适当的事情。
  • @Richard:你检查!start 有点太晚了(如果它是NULL,你不能在strstr() 调用中使用它)。
猜你喜欢
  • 2020-08-25
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
相关资源
最近更新 更多