c - 标记化后如何使字符串包含定界符?

标签 c

我刚开始在 Ubuntu 上学习 C 语言,我一直在尝试制作一个简单的 Shell,它的工作方式有点像 shell。所以,在我得到命令行之后,我想我可能必须用定界符分隔行。首先,我想使用“strtok_r()”用包含定界符的“&”delim 标记字符串,但是“strcat()”在某种程度上无法满足我的要求

我在生成标记后尝试使用“strcat()”。如果我使用该函数,第一个标记的输出与第二个标记配合良好,但会被丢弃。

输出就是这样。假设我有这些 token 。

token1 : abcde
token2 : fghij

然后如果我使用“strcat('&')”,它的输出就像

token1 : abcde&
token2 : &

我认为这可能是因为我试图放在“token1”末尾的定界符会影响“token2”的地址。

#include <stdio.h>
#include <string.h>

int main()
{
        static const char delim[] = "&";

        char str[256] = "sleep 5 & echo Hello & sleep 5; echo Hello";

        char *args[50];

        char *save;
        char *pBuf;
        int i = 0;

        for(pBuf = strtok_r(str, delim, &save);
                        pBuf;
                        pBuf = strtok_r(NULL, delim, &save)){

                printf("%d\n", i);
                args[i++] = pBuf;

        }


        /** OUT PUT START*/

        i = 0;

        while(args[i]){
                printf("args[%d] : %s\n", i , args[i]);
                i++;
        }

        /**OUT PUT END  */

        return 0;
}


********OUT PUT

args[0] : sleep 5
args[1] :  echo Hello
args[2] :  sleep 5; echo Hello

********EXPECTED OUT PUT

args[0] : sleep 5 &
args[1] : echo Hello &
args[2] : sleep 5; echo Hello 

最佳答案

问题是 strtok 在这种情况下有什么用。您可以使用 strchr 手动进行解析,而不是使事情复杂化。一旦找到分隔符 &,您就可以期待一个尾随空格并打印该空格和结尾,而不是开头。示例:

#include <string.h>
#include <stdio.h>

int main(void)
{
  const char str[256] = "sleep 5 & echo Hello & sleep 5; echo Hello";
  size_t length = strlen(str);

  const char* s1 = str;
  const char* s2;
  const char delim = '&';

  while(s1 < str+length)
  {
    s2 = strchr(s1, delim);
    if(s2 == NULL)
    {
      s2 = &str[length]; // point at null term
    }
    else
    {
      s2++; // point at space
    }
    printf("%.*s\n", s2-s1, s1); // print (s2-s1) characters
    s1 = s2+1; // point at next char after space, or 1 past null term
  }
}

输出:

sleep 5 &
echo Hello &
sleep 5; echo Hello

(请注意,在 C 中指向数组末尾后的 1 项是可以的,但不能取消对该地址的引用。)

关于c - 标记化后如何使字符串包含定界符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55742426/

相关文章:

c - 没有间接寻址是否可以实现子程序?

更改 GtkButton 的标签

C 中的 crypt() 函数不起作用

c - 使用 windows.h、C 截断文件

python - 如何在交互模式下将带有 matplotlib 的 Python 代码嵌入到 C 中?

c - 为什么要更改数组大小值来操作十进制字节?

c++ - 创建的文件中的文件 I/O

c - MacOS X : unexpected behavior of glGenFramebuffers()

C编程: Sorting a integer file while keeping their original place in file

c - 结构字段中的 strcpy/strncpy 段错误