【问题标题】:How do extract a sub string from a string after a certain character?如何在某个字符之后从字符串中提取子字符串?
【发布时间】:2019-07-08 21:29:37
【问题描述】:

我正在尝试实现重定向。我有来自用户的输入,我正在尝试从中提取输出文件。我正在使用 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);

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

【问题讨论】:

    标签: c substring


    【解决方案1】:

    当你这样做时:

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

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

    strcpy(output_file, chr_position + 1);
    

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

    【讨论】:

      【解决方案2】:

      您可以很容易地使用 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 添加到指针,使其最终指向我们希望提取的文本。

      【讨论】:

        猜你喜欢
        • 2012-09-25
        • 2014-11-24
        • 2015-04-10
        • 2018-08-21
        • 2022-08-10
        • 2021-10-30
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        相关资源
        最近更新 更多