c - 如何从字符串中提取某个字符后的子字符串?

标签 c substring

我正在尝试实现重定向。我有来自用户的输入,我正在尝试从中提取输出文件。我正在使用 strstr() 来查找第一次出现的“>”。从那里我可以提取字符串的其余部分,但我不确定如何完成此操作。

我尝试过将 strstr() 与 strcpy() 一起使用,但没有成功。

// char_position is the pointer to the character '>'
// output_file is the file that I need to extract
// line is the original string

// example of input: ls -l > test.txt

char *chr_position = strstr(line, ">");
char *output_file = (char *) malloc(sizeof(char) * (strlen(line) + 1));
strcpy(output_file + (chr_position - line), chr_position // something here?);
printf("The file is %s\n", output_file);

预期结果是从 > 到行尾构建一个字符串。

最佳答案

当你这样做时:

strcpy(output_file + (chr_position - line), chr_position);

您开始复制到output_file,而不是在开头,而是在之后复制到chr_position - line字节。从头开始:

strcpy(output_file, chr_position + 1);

另请注意,由于 chr_position 指向 > 字符,因此您希望在该字符之后开始复制至少 1 个字节。

关于c - 如何从字符串中提取某个字符后的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697445/

相关文章:

c - RSA_private_encrypt 总是失败

c# - 使用超出范围的子字符串拆分字符串

Python:比较两个字符串并返回它们共有的最长段

javascript - 功能:根据字符串中是否存在子字符串返回 True/False

c - 错误: comparison between a pointer and an integer

java - Java 是一种编写简单机器人/守护进程的好语言吗(当 RAM 有限时!)?

c - 升级到 Windows 10 后不再具有通过 gcc 编译的权限

python - 将非 UTF-8 字符转换为 UTF-8

java - 使用 indexOf 将占位符替换为 Map 值

MySQL 在一列的最后 5 个字符内搜索?