从字符串中删除括号中的文本?

时间:2019-04-17 21:07:19

标签: c string position

我的任务是从字符串中查找和删除括号中的文本。我的想法是计算第一个'('和最后一个')'的位置,然后从'('位置删除d个字符,问题是,如果实际上存在某些内容,则'('和')'的位置将替换为0。括号。


void task(char *s)
{
    int i,d;
    int j=0;  //position of first '('
    int k=0; //add 1 for every character in parentheses until reach ')'
    for(i=0; i<strlen(s); i++)
    {   
        if(s[i]=='(')
        {
        j=i;
        }
            else{
            if(s[i]==')') 
            k=i;
            printf("k=%d \n",k);
            }

    }
    d=(k-j-1);
}
void deleteptext(char *x,int a, int b)
{
    if((a+b-1)<=strlen(x))
    {
        strcpy(&x[b-1],&x[a+b-1]);
        puts(x);
    }
}
int main()
{
    puts("Text: ");
    gets(s);
    task(s);
    deleteptext(s,j,d);
}   

例如,如果我的输入是abc (def),则输出是相同的(需要abc),“ j”值在某一点是4,但遇到“ d”。

1 个答案:

答案 0 :(得分:1)

您的程序未编译,您假设可以在 task d 的局部变量 j main 中访问em>是未知等,并且您使用 strcpy ,而源和目标可能会重叠并且不赞成使用 gets

使用 strchr strrchr memmove 的提案:

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

int main()
{
  puts("Text : ");

  char s[256];

  if (fgets(s, sizeof(s), stdin) == NULL)
    return -1;

  /* may be remove \n from s */

  char * p1 = strchr(s, '(');

  if (p1 == NULL)
    fprintf(stderr, "'(' is missing\n");
  else {
    char * p2 = strrchr(p1+1, ')');

    if (p2 == NULL)
      fprintf(stderr, "')' is missing\n");
    else {
      memmove(p1, p2 + 1, strlen(p2 + 1) + 1);
      puts(s);
    }
  }

  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra p.c
pi@raspberrypi:/tmp $ ./a.out
Text : 
aze(qsd)wxc
azewxc

请注意,即使有多个'('或')'也删除了第一个'('和最后一个')'之间的所有内容:

pi@raspberrypi:/tmp $ ./a.out
Text : 
aze((qsd)wxc
azewxc

pi@raspberrypi:/tmp $ ./a.out
Text : 
aze(qsd)iop)wxc
azewxc