c - 删除字符串中括号之间的子字符串

标签 c string strtok

我需要删除括号之间的每个子字符串。我找到了一些解决方案,但没有一个是好的。这是一个例子:

我的字符串是:text(lorem(ipsum)abcd)pieceoftext 实际输出:lorem(ipsum

然而,预期的输出:text(())pieceoftexttextpieceoftext

这是代码。我已经没有想法了。我想到了使用 strtok()但我有两个不同的分隔符。

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

int main()
{
    const char *s = "text(lorem(ipsum)abcd)pieceoftext";
    const char *patternA = "(";
    const char *patternB = ")";
    char *target = NULL;
    char *start, *end;

    if (start = strstr( s, patternA ))
    {
        start += strlen( patternA);
        if (end = strstr( start, patternB ) )
        {
            target = (char *)malloc(end - start + 1);
            memcpy(target, start, end - start);
            target[end - start] = '\0';
        }
   }
   if (target)
      printf("Answer: %s\n", target);
   return 0;
}

期待听到您的一些想法来解决这个问题。谢谢

最佳答案

首先,只需为 target 分配足够的内存,因为您需要保存整个源字符串 s,因为您真的不知道需要多少空间.请记住为字符串结尾字符添加一个。

然后将 patternApatternBchar * 更改为 char,这样你就可以将它们与个人进行比较s 中的字符。

然后您需要遍历源字符串,跟踪您是否在括号内。由于您需要支持嵌套括号,因此我会使用一个计数器来计算您在括号内的深度:

int main()
{
    const char *s = "text(lorem(ipsum)abcd)pieceoftext";
    const char patternA = '(';
    const char patternB = ')';
    char *target;
    int targetIndex = 0;
    int parenDepth = 0;

    target = malloc(strlen(s) + 1);
    // check for malloc() error

    for (int sourceIndex = 0; sourceIndex < strlen(s); sourceIndex++) {
        if (s[sourceIndex] == patternA) {
            // we are going deeper into parens, add to level, then ignore the char
            parenDepth++;
            continue;
        }

        if (s[sourceIndex] == patternB) {
            // we are coming out of the parens, lower our level, ignore the parens char
            parenDepth--;
            continue;
        }

        if (parenDepth == 0) {
            // if depth is 0, then we are not inside parens, so copy the char to target
            target[targetIndex++] = s[sourceIndex];
        }
    }

    // add end-of-string
    target[targetIndex] = '\0';

    printf("Answer: %s\n", target);

    return 0;
}

关于c - 删除字符串中括号之间的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50320770/

相关文章:

c - 所有数字相加

Java每n行追加换行符

c - 下面的 while 循环有什么问题?

python 将 split 和 join 组合成 1 行代码

javascript - 修改键值对Javascript中的字符串

c - 使用 strtok [C] 程序崩溃

c - 在 C 中将文件 Strtok 放入数组中

C、结构只写4个字符

python - 在 Python 中重现一个 C 函数指针数组

c - 获取进程的 pid,了解其使用的 Linux header 中的结构