You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除字符串中括号间子串?嵌套括号场景代码待优化

解决嵌套括号内子串移除问题

你的代码目前只能处理单层无嵌套的括号,但遇到像(lorem(ipsum)abcd)这种嵌套括号时,strstr只会找到第一个(和第一个),导致结果完全不符合预期。要处理嵌套括号,我们需要跟踪括号的深度层级,用计数器(或栈,不过计数器更简单)来判断当前字符是否处于括号内部。

下面分两种你期望的输出场景给出解决方案:

场景1:保留外层括号,清空括号内所有内容(输出text(())pieceoftext)

这个场景的核心逻辑是:只保留字符串中非括号区域的内容,以及所有的括号本身,括号中间的内容全部丢弃。我们用一个计数器depth来记录当前括号的深度:

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

int main() {
    const char *s = "text(lorem(ipsum)abcd)pieceoftext";
    int len = strlen(s);
    // 分配足够的内存存储结果(最多和原字符串一样长)
    char *result = (char *)malloc(len + 1);
    if (!result) {
        perror("malloc failed");
        return 1;
    }

    int depth = 0;
    int idx = 0; // 结果字符串的索引

    for (int i = 0; i < len; i++) {
        char c = s[i];
        if (c == '(') {
            depth++;
            result[idx++] = c; // 保留左括号
        } else if (c == ')') {
            depth--;
            result[idx++] = c; // 保留右括号
        } else if (depth == 0) {
            // 不在括号内部,保留当前字符
            result[idx++] = c;
        }
        // 处于括号内部且不是括号的字符,直接跳过
    }

    result[idx] = '\0'; // 字符串结束符
    printf("Answer (保留括号): %s\n", result);
    free(result);
    return 0;
}

场景2:完全移除所有括号及其内部内容(输出textpieceoftext)

这个场景更简单:只要处于括号内部(depth>0),所有字符(包括括号本身)都丢弃,只保留非括号区域的内容:

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

int main() {
    const char *s = "text(lorem(ipsum)abcd)pieceoftext";
    int len = strlen(s);
    char *result = (char *)malloc(len + 1);
    if (!result) {
        perror("malloc failed");
        return 1;
    }

    int depth = 0;
    int idx = 0;

    for (int i = 0; i < len; i++) {
        char c = s[i];
        if (c == '(') {
            depth++;
        } else if (c == ')') {
            depth--;
        } else if (depth == 0) {
            // 只有不在括号内部时才保留字符
            result[idx++] = c;
        }
        // 括号和括号内的内容全部跳过
    }

    result[idx] = '\0';
    printf("Answer (移除括号): %s\n", result);
    free(result);
    return 0;
}

为什么strtok不适用?

strtok是基于单一分隔符集合来分割字符串的,它无法识别括号的成对嵌套关系——比如它会把所有(和)都当成分隔符,完全无法区分哪个(对应哪个),所以处理嵌套括号场景时,strtok根本派不上用场,必须用深度跟踪的方式。

内容的提问来源于stack exchange,提问作者user8451776

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:28:47