gpt4 book ai didi

c - 如何删除 C 中字符串的子字符串

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:03 25 4
gpt4 key购买 nike

我很难在 C 中获取字符串的子字符串。例如,如果我有一个

char *buff = "cat –v <  x y z | ";
char *p = strtok (buff, " ");
while (p != NULL)
{
if (!strcmp(p, "<") && !isredirected)
{
isredirected = 1;
infileindex = tokenscounter + 1;
inputredirectionindex = tokenscounter;
}
commandsArray[tokenscounter++] = p;
p = strtok (NULL, " ");

}

从这个 buff 字符串中,我想删除 '<''|' 之间的任何字符串。那就是删除 x y z 。我使用 strtok 解析所有标记,但无法删除那个 x y z。在我找到 '<' 之后,我想摆脱 < 之后和 |

之前的所有标记

最佳答案

我通常会为此推荐正则表达式,当然不是 strtok,更不用说字符串文字了(未定义的行为,参见 C's strtok() and read only string literals)

只有基本库的一种解决方案是:

  • 寻找起始字符串/字符
  • 寻找结束字符串/字符
  • 用开始字符串之前的部分与结束字符串之后的部分组装重建一个字符串(长或短)。

我正在为此使用 strstr。它是内置的,不需要循环,适用于多字符模式。

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

int main()
{
const char *buff = "cat -v < x y z | hello";
const char *start_pattern = "<";
const char *end_pattern = "|";

const char *start = strstr(buff,start_pattern);
if (start)
{
const char *end = strstr(start,end_pattern);
if (end)
{
// allocate enough memory
char *newbuff = malloc(strlen(buff)+1);

int startlen = start-buff; // length of the start of the string we want to keep

strncpy(newbuff,buff,startlen); // start of the string
strcpy(newbuff+startlen,end+strlen(end_pattern)); // end of the string

printf("Result:%s\n",newbuff);
free(newbuff); // free the memory
}
}

}

编辑:同时,一些代码已添加到问题中。这说明我没有考虑到它,因为我试图编写一个不那么笨拙的解决方案。

关于c - 如何删除 C 中字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50495973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com