2011-09-06 8 views
5

カッコ内の文字を削除するプログラムを作成しました。入力されたテキストには、開き、閉じ括弧が一致する必要があります。Cのカッコ内の文字を削除する

ケース1:

入力:      (Hello) World
出力:World

ケース2:

入力:      (Hello World
出力:(Hello World

ケース3:

入力:      Hello)(World
出力:Hello)(World

ケース4:

入力:      Hello((hi) World)
出力:Hello

ケース5:

入力:      (Hello) hi (World)
出力:hi

は、ここに私のコードです:

#include <stdio.h> 
int main(){ 
    char string[100] = {0}; 
    char removedletters[100] = {0}; 
    fgets(string, 100, stdin); 
    char *p; 
    int x = 0; 
    int b = 0; 
    for (p=string; *p!=0; p++) { 
     if (*(p-1) == '(' && x) { 
      x = 0; 
     } 
     if (*p == ')') { 
      x = 1; 
     } 
     if (!x){ 
      removedletters[b] = *p; 
      b++; 
     } 
    } 
    puts(removedletters); 
} 

ケース1、3、5は何ケース2及び4 に正しいですが、ではありません私のコードに間違っていますか?

+0

使用strchrの代わりに、(*(P-1)は '最初の反復のために未定義の動作であれば、文字列 – thumbmunkeys

+0

'を使用して手動で検索する。 – Mat

+0

1はStackOverflowのへようこそ!グレート最初の質問を。 – phihag

答えて

2

あなたは未定義の動作を起動されています

for(p=string; *p!=0; p++){ 
    if(*(p-1) == '(' && x){ 
     x = 0; 
    } 

初めてp++が評価されるがゆえ、初めて、*(p-1)はあなたすなわち、stringの1つの左を向いている、ループ・ブロックの末尾にあります*(string-1)を行っています。

未定義の動作がある場合、残念ながら、保証は失われます。

1

効率的には、最後に見つかった(文字のスタックを保持して、)が見つかるたびに部分を削除します。半擬似コードで

// str is the input string, set up to and from pointers. 
stacktype stack = empty-stack 
char *from = str 
char *to = str 

// Process every character once and once only. 
while *from != '\0': 
    switch *from: 
     // Open, transfer character and store position on stack. 
     case '(': 
      *to++ = *from++ 
      stack.push (to - 1) 
      break 

     // Close, get most recent '(' and adjust to for overwrite. 
     // If no most recent, just transfer as is. 
     case ')': 
      if stack is not empty: 
       to = stack.pop() 
      else: 
       *to++ = *from++ 
      break 

     // Anything else, just transfer. 
     default: 
      *to++ = *from++ 

// Terminate string at truncated position. 
*to = '\0' 

これは、スタック内のすべての(位置を覚えるが、まだ文字を転送し、文字列で文字を通過します。

あなたが)文字を見つけるたびに、あなたが最も最近の(文字から上書きを開始するように、あなたが効果的に内部のすべてを削除し、(...)セクションを含め、toポインタを調整します。

関連する問題