Romi-知行合一

轻轻的风轻轻的梦,轻轻的晨晨昏昏, 淡淡的云淡淡的泪,淡淡的年年岁岁。
  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

字符串处理——()的匹配问题

Posted on 2012-09-22 20:33  romi  阅读(446)  评论(0编辑  收藏  举报

判断字符串中‘(’与‘)’是否匹配,匹配返回1,不匹配返回0

 1 #include <iostream>
 2 #include <string.h>
 3 
 4 using namespace std;
 5 
 6 bool Check(char *str)
 7 {
 8     int len=strlen(str);
 9     int tag=0;
10     for (int i=0;i<len;i++)
11     {
12         //判断'('
13         if (tag==0)
14         {
15             if (str[i]=='(')
16             {
17                 tag=1;
18                 continue;//一定要加,字符判断完毕,结束本次循环
19             }
20             if (str[i]==')')
21             {
22                 return false;
23             }
24         }
25         //判断')'
26         if (tag==1)
27         {
28             if (str[i]==')')
29             {
30                 tag=0;
31                 continue;
32             }
33             if (str[i]=='(')
34             {
35                 return false;
36             }
37         }
38     }
39     if (tag==0)
40     {
41         return true;
42     }
43     if (tag==1)
44     {
45         return false;
46     }
47 }
48 
49 int main()
50 {
51     char str[]="()ab(cd)efgh";
52     bool dd=Check(str);
53     cout<<dd<<endl;
54 
55     return 0;
56 }

需要特别注意的是两个continue,判断完后结束该次循环。