[英]Removing characters inside parenthesis in 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中沒有。我的代碼有什么問題?
您正在調用未定義的行為:
for(p=string; *p!=0; p++){
if(*(p-1) == '(' && x){
x = 0;
}
第一次評估p++
是在循環塊的末尾,因此,第一次, *(p-1)
指向string
左邊一個,即你正在做*(string-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'
這將逐個字符地逐字符串,記住所有(
堆棧中的位置但仍然傳輸字符)。
每當你找到a )
字符時,你調整to
指針,以便從最新的字符開始覆蓋(
字符,有效地刪除內部的所有內容,包括(...)
部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.