C Puzzles

yet another place for C puzzles

Monday, February 19, 2007

 

curly bracket matching

Not a puzzle exactly.

Q. Are you familiar with curly bracket matching in vi editor?
(FYI: you may use % to find matching curly brackets)

implement this feature in 'your own' editor.

[you may even give a single-WORD-answer :-]

To simplify the question...
imagine a text with curly brackets like the following
"{{}{{}{}}{}}"

Input/output:
2nd curly matches with 3rd
1st curly with last one
4th with 9th

Now start writing the program.

Comments:
This is the program ......

string strInput = TextBox1.Text;
String[] arrCh = new String[strInput.Length];
int a = 0;
foreach (char ch in strInput)
{
arrCh[a] = ch.ToString();
a++;
}
Boolean bulStatus = false;
for (int i = 0; i < arrCh.Length; i++)
{
if (arrCh[i] == "{")
{
int CountTrue = 0;
for (int j = i+1; j < arrCh.Length; j++)
{
if (arrCh[j] == "{")
{
bulStatus = true;
CountTrue++;
}
if (arrCh[j] == "}")
{
if (!bulStatus)
{
if (CountTrue == 0)
{
Response.Write("The bracket start at " + (i + 1).ToString() + " and ending at " + (j + 1).ToString() + "\n");
bulStatus = false;
break;
}
}
else
{
bulStatus = false;
}
CountTrue--;
}
}
}
}
 
I can give a logic:
Use a stack and an array
Stack:
push() on {
pop() on }
array:
store index position of braces in corresponding index so that it could b used to find which '}' has matched to '}'
 
Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2005   August 2005   October 2005   December 2005   March 2006   June 2006   July 2006   December 2006   February 2007   June 2007   March 2010   May 2010  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]