[英]How do extract a sub string from a string after a certain character?
我正在尝试实现重定向。 我有来自用户的输入,我正在尝试从中提取输出文件。 我正在使用 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 个字节。
您可以很容易地使用 strstr 来完成此操作:
char inarg[] = "ls -l > test.txt";
char *pos;
pos = strstr(inarg, "> ") + 2;
printf("%s\n", pos); // Will print out 'test.txt'
这是通过在字符串中查找 "> " 组合来实现的。 strstr 调用后的 +2 是为了允许 strstr 将返回一个指向字符串 '> test.txt' 的指针,我们想跳过 '> '(带有尾随空格的 2 个字节),因此我们将 2 添加到指针,以便它最终指向我们希望提取的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.