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

问题描述 投票:0回答:1

我的任务是从字符串中查找和删除括号中的文本。我的想法是计算第一个'('和最后')'的位置,然后从''''位置删除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”时它返回到0。

c string position
1个回答
1
投票

你的程序没有编译,你认为你可以访问任务的本地变量j的主要部分,d是未知等,并且你使用strcpy而源和目的地可能重叠并且不赞成获取

使用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

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

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

pi@raspberrypi:/tmp $ ./a.out
Text : 
aze(qsd)iop)wxc
azewxc
© www.soinside.com 2019 - 2024. All rights reserved.