刪除給定輸入中括號的 C 程式。
問題
讓我們透過刪除括號來建立簡化表示式。
解決方案
示例 1
Input: A string expression with bracket is as follows: (x+y)+(z+q) The output is as follows: x+y+z+q
示例 2
The input is as follows: (x-y+z)-p+q The output is as follows: x-y+z-p+q
演算法
參考一種演算法,從給定的輸入中刪除括號。
步驟 1:在執行時宣告並讀取輸入。
步驟 2:遍歷字串。
步驟 3:將輸入字串的每個元素複製到新字串中。
步驟 4:如果遇到任何圓括號作為元素,則用空格替換它。
示例
以下是刪除給定輸入中括號的 C 程式 −
#include<stdio.h> int main(){ int i=0,c=0,j=0; char a[100],b[100]; printf("
Enter the string :"); scanf("%s",a); while(a[i]!='\0'){ if((a[i]=='(') && (a[i-1]=='-')){ (c=0)?j=i:j=c; while(a[i]!=')'){ if(a[i+1]=='+') b[j++]='-'; else if(a[i+1]=='-') b[j++]='+'; else if(a[i+1]!=')') b[j++]=a[i+1]; i++; } c=j+1; } else if(a[i]=='(' && a[i-1]=='+'){ (c==0)?j=i:j=c; while(a[i]!=')'){ b[j++]=a[i+1]; i++; } j–; c=j+1; } else if(a[i]==')'){ i++; continue; } else { b[j++]=a[i]; } i++; } b[j]='\0'; printf("%s",b); return 0; }
輸出
當執行上述程式時,它會產生以下輸出 −
Enter the string:(x+y)-z x+y-z
廣告