I am new to Coding and at present i am working on NodeJs file system module.
I am working on a file which contains large data and that data stored as a string.
My problem is , I am not able to find the matching close brace and position of '}'.
{ // I know the index of '{'
{
{
}
{
}
}
{
{
}
}
} // have to find position here.
Assuming that you want to have a program to do it!!!
Just compare one by one until the matching brace found. Code might be something similar to this (not tested) -
var string = "{{{}}}";
var leftCurlyBraceIndex = 0, // index of the '{' to which you need to find the matching '}'
rightCurlyBracesTobeIgnored = 0,
rightCurlyBraceIndex = -1;
for (var i = leftCurlyBraceIndex + 1, l = string.length; i < l; i++) {
if (string[i] == "}") {
if (rightCurlyBracesTobeIgnored == 0) {
rightCurlyBraceIndex = i; break;
} else {
rightCurlyBracesTobeIgnored -= 1;
}
} else if (string[i] == "{"){
rightCurlyBracesTobeIgnored += 1;
}
}
alert(rightCurlyBraceIndex )
var str = '{{{}{}}{{}}}', matchBrace;
matchBrace = function(str, i) {
var index = 0, leftBraces = [], len;
if(str.charAt(i) === '}') {
return -1;
}
for(index = i, len = str.length; index < len; ++index) {
if(str.charAt(index) === '{') {
leftBraces.push('{');
}
if(str.charAt(index) === '}') {
if(leftBraces.length === 1) {
return index;
}
leftBraces.pop()
}
}
};