我需要删除括号之间的每个子字符串。我找到了一些解决方案,但没有一个是好的。这是一个例子:
我的字符串是:text(lorem(ipsum)abcd)pieceoftext 实际输出:lorem(ipsum强>
然而,预期的输出:text(())pieceoftext 或 textpieceoftext
这是代码。我已经没有想法了。我想到了使用 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
,因为您真的不知道需要多少空间.请记住为字符串结尾字符添加一个。
然后将 patternA
和 patternB
从 char *
更改为 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/