Pairing html tags using c#? -
trying create html checker using c#, can't figure out how check if 2 html tags correctly paired <body></body>
. managed relevant tags dictionary (the closing tags /
in front), in order appeared in input. can check opening tags don't close (or vice versa).
but can't figure out how check if pairs of tags overlapping. e.g.
<body><title></body></title>
|____________| |______________|
(there many many pairs)
to clarify, question pair matching, not else html, thanks!
if want match pairs of tags (non-paired tags aside), consider following:
- go left right, enumerating tags;
- if see opening tag, put in on stack;
- if see closing tag, check if corresponding opening tag on top of stack; if yes - pop it, otherwise report error;
- at end, check if stack empty.
let me illustrate idea using brackets instead of tags simplicity. function checks if brackets ()[]{}
balanced.
static bool checkstring(string s) { var stack = new stack<char>(); foreach(char c in s) if("([{".contains(c)) stack.push(c); else if(")]}".contains(c)) { if(stack.count == 0) return false; char d = stack.pop(); if(d == '(' && c != ')' || d == '[' && c != ']' || d == '{' && c != '}') return false; } return stack.count == 0; }
Comments
Post a Comment