-1

C 并没有使这变得容易。我四处张望,什么也没找到。

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

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

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

4

1 回答 1

3

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 调用,这并不难。

于 2012-03-14T21:11:07.967 回答