C#, Finding equal amount of brackets - c#

I've made my own way to check if the amount of () and "" are equal. So for example "H(ell)o") is correct. However, the problem I face is that what if the first bracket is ) and the other is ( example "H)ell(o" this would mean it's incorrect. So my question is how would I check whether the first bracket in any word is opening?
EDIT:
public static Boolean ArTinkaSintakse(char[] simboliai)
{
int openingBracketsAmount = 0;
int closingBracketsAmount = 0;
int quotationMarkAmount = 0;
for (int i = 0; i < simboliai.Length; i++)
{
if (openingBracketsAmount == 0 && simboliai[i] == ')')
break;
else if (simboliai[i] == '\"')
quotationMarkAmount++;
else if (simboliai[i] == '(')
openingBracketsAmount++;
else if (simboliai[i] == ')')
closingBracketsAmount++;
}
int bracketAmount = openingBracketsAmount + closingBracketsAmount;
if (quotationMarkAmount % 2 == 0 && bracketAmount % 2 == 0)
return true;
else
return false;
}

Add a check for if (openingBracketsAmount < closingBracketsAmount). If that's ever true, you know that the brackets are unbalanced.

Add an if statement that breaks out of the loop if the first bracket encountered is a closing bracket, like so:
for (int i = 0; i < word.Length; i++)
{
if ((openingBracketsAmount == 0) && (word[i] == ')'))
{
<Log error...>
break;
}
<Rest of your loop...>
}
This way, as soon as openingBracketsAmount is updated, this if statement will be unreachable.

I would approach the problem recursively.
Create a Dictionary<char, char> to keep track of which opening character goes with which closing one.
Then I would implement:
boolean findMatches(string input, out int lastIndex) {}
The method will scan until a member of the Dictionary keys is found. Then it will recursively call itself with the remainder of the string. If the recursive call comes back false, return that. If true, check if the lastIndex character (or the one after; I always need to write the code to check fenceposts) is the matching bracket you want. If it is, and you're not at the end of the string, return the value of a recursive call with the rest of the string after that matching bracket. If you are at the end, return true with that character's index. If that character isn't the matching bracket/quote, pass the remainder of the string (including that last character) to another recursive call.
Continue until you reach the end of the string (returning true if you aren't matching a bracket or quote, false otherwise). Either way with a lastIndex of the last character.

Probably you need a stack-based approach to validate such expressions.
Please try the following code:
public static bool IsValid(string s)
{
var pairs = new List<Tuple<char, char>>
{
new Tuple<char, char>('(', ')'),
new Tuple<char, char>('{', '}'),
new Tuple<char, char>('[', ']'),
};
var openTags = new HashSet<char>();
var closeTags = new Dictionary<char, char>(pairs.Count);
foreach (var p in pairs)
{
openTags.Add(p.Item1);
closeTags.Add(p.Item2, p.Item1);
}
// Remove quoted parts
Regex r = new Regex("\".*?\"", RegexOptions.Compiled | RegexOptions.Multiline);
s = r.Replace(s, string.Empty);
var opened = new Stack<char>();
foreach (var ch in s)
{
if (ch == '"')
{
// Unpaired quote char
return false;
}
if (openTags.Contains(ch))
{
// This is a legal open tag
opened.Push(ch);
}
else if (closeTags.TryGetValue(ch, out var openTag) && openTag != opened.Pop())
{
// This is an illegal close tag or an unbalanced legal close tag
return false;
}
}
return true;
}

Related

Remove set of elements in an char array

I have a char array where I have to remove the elements from the same if I find the certain char. For eg: "paragraphs" is assigned in an char array. I have given search keyword as 'g'. If it is found then I have to remodify the original char array as "raphs" by removing all elements including the found one.
char[] ch = "paragraphs"
search chr = 'g'
Desired result(if chr found):
char[] ch = "raphs"
To explain bit clearer
I have to write a func. to find whether str(user input) contains all the char of the word "abcdef" in the same sequence as specify in the "abcdef". Return True if contains all the char in the same sequence or else false.
User Input: fgajbdcmdgeoplfqz
Output: true
User Input: asrbcyufde
Output: false
You can use LINQ's SkipWhile, which will skip elements until the search character is found.
An additionnal Skip is necessary to obtain raphs instead of graphs, and the ToArray() for the input string and result because you want to work with arrays.
char[] ch = "paragraphs".ToArray();
char search = 'g';
ch = ch.SkipWhile(c => c != search).Skip(1).ToArray(); // raphs
But honestly since your input is a string, I'd work with that:
string ch = "paragraphs";
char search = 'g';
ch = ch.Substring(ch.IndexOf(search) + 1);
and, if really necessary, convert it with .ToArray() afterwards.
And now to answer your 'clarification' (which is pretty much an other question by the way).
There are probably better ways to do it, but here's something that will accomplish what you want in O(n)
private bool ContainsInSequence(string input, string substring)
{
int substringIndex = 0;
for (int i = 0; i < input.Count(); i++)
{
if (input[i] == substring[substringIndex])
{
substringIndex++;
if (substringIndex == substring.Length)
{
return true;
}
}
}
return false;
}
Basically, you go through the input string in order, and each time you encounter the current letter from your substring you move to the next one.
When you reach the end of the substring, you know the input string contained all your substring, so you return true.
If we're not at the end after going through all the input this means there was a letter either out of order or missing, so we return false.
ContainsInSequence("fgajbdcmdgeoplfqz", "abcdef"); // true
ContainsInSequence("asrbcyufde ", "abcdef"); // false
ContainsInSequence("abcdfe", "abcdef"); // false
Try
char[] ch = "paragraphs".ToCharArray();
int index = Array.IndexOf(ch, 'g');
char[] result = new string(ch).Substring(index+1).ToCharArray();
Here's my version without using Linq:
static void Main(string[] args)
{
Console.WriteLine("Please provide a list of characters");
string Charactersinput = Console.ReadLine();
Console.WriteLine("Please provide the search character");
char Searchinput = Console.ReadKey().KeyChar;
Console.WriteLine("");
List<char> ListOfCharacters = new List<char>();
//fill the list of characters with the characters from the string
// Or empty it, if th esearch charcter is found
for (int i = 0; i < Charactersinput .Length; i++)
{
if (Searchinput == Charactersinput[i])
{
ListOfCharacters.Clear();
}
else
ListOfCharacters.Add(Charactersinput [i]);
}
//get your string back together
string Result = String.Concat(ListOfCharacters);
Console.WriteLine("Here's a list of all characters after processing: {0}", Result);
Console.ReadLine();
}
To answer your "clarification" question, which is very different from the original question:
I have to write a func. to find whether str(user input) contains all
the char of the word "abcdef" in the same sequence as specify in the
"abcdef". Return true if contains all the char in the same sequence or
else false.
Input: fgajbdcmdgeoplfqz Output: true
Input: asrbcyufde Output: false
The following function takes in two strings, a source string to search and a string containing the sequence of characters to match. It then searches through the source string, looking for each character (starting at the found position of the previous character). If any character is not found, it returns false. Otherwise it returns true:
public static bool ContainsAllCharactersInSameSequence(string sourceString,
string characterSequence)
{
// Short-circuit argument check
if (sourceString == null) return characterSequence == null;
if (characterSequence == null) return false;
if (characterSequence.Length > sourceString.Length) return false;
if (sourceString == characterSequence) return true;
int startIndex = 0;
foreach (char character in characterSequence)
{
int charIndex = sourceString.IndexOf(character, startIndex);
if (charIndex == -1) return false;
startIndex = charIndex + 1;
}
return true;
}

Writing a recursive function in C#

I need to write a function which verifies parentheses are balanced in a string. Each open parentheses should have a corresponding close parentheses and they should correspond correctly.
For example, the function should return true for the following strings:
(if (any? x) sum (/1 x))
I said (it's not (yet) complete). (she didn't listen)
The function should return false for the following strings:
:-)
())(
OPTIONAL BONUS
Implement the solution as a recursive function with no mutation / side-effects.
Can you please help me out in writing using C# because I'm new to .NET technologies.
Thanks.
Here's what I've tried so far. It works for sending parameters as open and close brackets, but I'm confused with just passing a string... and also I should not use stack.
private static bool Balanced(string input, string openParenthesis, string closedParenthesis)
{
try
{
if (input.Length > 0)
{
//Obtain first character
string firstString = input.Substring(0, 1);
//Check if it is open parenthesis
//If it is open parenthesis push it to stack
//If it is closed parenthesis pop it
if (firstString == openParenthesis)
stack.Push(firstString);
else if (firstString == closedParenthesis)
stack.Pop();
//In next iteration, chop off first string so that it can iterate recursively through rest of the string
input = input.Substring(1, input.Length - 1);
Balanced(input, openParenthesis, closedParenthesis); //this call makes the function recursive
}
if (stack.Count == 0 && !exception)
isBalanced = true;
}
catch (Exception ex)
{
exception = true;
}
return isBalanced;
}
You don't need to use any recursion method for such a simple requirement, just try this simple method and it works like a charm:
public bool AreParenthesesBalanced(string input) {
int k = 0;
for (int i = 0; i < input.Length; i++) {
if (input[i] == '(') k++;
else if (input[i] == ')'){
if(k > 0) k--;
else return false;
}
}
return k == 0;
}
I have used the startIndex and increment with each recursive call
List<string> likeStack = new List<string>();
private static bool Balanced(string input, string openParenthesis, string closedParenthesis , int startIndex)
{
try
{
if (startIndex < input.Length)
{
//Obtain first character
string firstString = input.Substring(startIndex, 1);
//Check if it is open parenthesis
//If it is open parenthesis push it to stack
//If it is closed parenthesis pop it
if (firstString == openParenthesis)
likeStack.Add(firstString);
else if (firstString == closedParenthesis)
likeStack.RemoveAt(likeStack.Count -1);
//In next iteration, chop off first string so that it can iterate recursively through rest of the string
Balanced(input, openParenthesis, closedParenthesis , startIndex + 1); //this call makes the function recursive
}
if (likeStack.Count == 0 && !exception)
isBalanced = true;
}
catch (Exception ex)
{
exception = true;
}
return isBalanced;
}
How's this recursive version?
public static bool Balanced(string s)
{
var ix = -1;
return Balanced(s, false, ref ix);
}
private static bool Balanced(string s, bool inParens, ref int ix)
{
ix++;
while (ix < s.Length)
{
switch (s[ix++])
{
case '(':
if (!Balanced(s, true, ref ix))
return false;
break;
case ')':
return inParens;
}
}
return !inParens;
}

How to find the matching pair of braces in a string?

Suppose I have a string "(paid for) + (8 working hours) + (company rules)" . Now I want to check whether this complete string is surrounded with parentheses or not. Basically I want to check if the string is like this or not : "((paid for) + (8 working hours) + (company rules))". If it is already surrounded with parentheses, then I will leave it as it is, otherwise I will apply parentheses to the complete string so that the ouput is : "((paid for) + (8 working hours) + (company rules))" . By counting the number of parentheses, I am not able to solve this problem.
Can anyone please suggest a solution?
The Stack is a good idea, but as you want to see if the complete string is surrounded with parens, i suggest you put the index of the encountered opening paren on the Stack. That way, each time you pop an item on the stack, check if it's 0, meaning the opening paren that corresponds to this closing paren was on the beginning of the string. The result of this check for the last closing paren will tell you if you need to add parens.
Example:
String s = "((paid for) + (8 working hours) + (company rules))";
var stack = new Stack<int>();
bool isSurroundedByParens = false;
for (int i = 0; i < s.Length; i++) {
switch (s[i]) {
case '(':
stack.Push(i);
isSurroundedByParens = false;
break;
case ')':
int index = stack.Any() ? stack.Pop() : -1;
isSurroundedByParens = (index == 0);
break;
default:
isSurroundedByParens = false;
break;
}
}
if (!isSurroundedByParens) {
// surround with parens
}
use a stack.. as in when u find a ( bracket push it and when u see ) pop the stack..
Finally when the string is parsed completely the stack should be empty... This will ensure you that the brackets are not missing..
in your case if in between the stack becomes empty then there are no surrounding brackets for entire string
for example:
for input string:
(paid for) + (8 working hours) + (company rules)
the first ( would be pushed and when it encounters the ) it will pop the stack, now check if there is more string to be parsed and stack is not empty. If stack is empty that means the entire string is not in bracket.
whereas for the string:
((paid for) + (8 working hours) + (company rules))
stack will not be empty untill the last ) appears.
Hope this helps...
Finds the closing bracket index
public int FindClosingBracketIndex(string text, char openedBracket = '{', char closedBracket = '}')
{
int index = text.IndexOf(openedBracket);
int bracketCount = 1;
var textArray = text.ToCharArray();
for (int i = index + 1; i < textArray.Length; i++)
{
if (textArray[i] == openedBracket)
{
bracketCount++;
}
else if (textArray[i] == closedBracket)
{
bracketCount--;
}
if (bracketCount == 0)
{
index = i;
break;
}
}
return index;
}
Tests
static void Main()
{
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded(""));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("("));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded(")"));
Console.WriteLine("Expected: {0}, Is: {1}", true, IsSurrounded("()"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(()"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("())"));
Console.WriteLine("Expected: {0}, Is: {1}", true, IsSurrounded("(.(..)..(..)..)"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(..)..(..)"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(..)..(..)..)"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(.(..)..(..)"));
}
Method
Very fast
No stack
No loop through entire string
If the first opening parenthesis has its closing counterpart, then the result can't be true. Same thing about last closing parenthesis.
static bool IsSurrounded(string text)
{
if (text.Length < 2 || text.First() != '(' || text.Last() != ')')
return false;
for (var i = 1; i < text.Length - 1; i++)
{
if (text[i] == ')')
return false;
if (text[i] == '(')
break;
}
for (var i = text.Length - 2; i > 0; i--)
{
if (text[i] == '(')
return false;
if (text[i] == ')')
break;
}
return true;
}
Limitations
Should be not used when there are more recursive parentheses such as ((..)) + ((..))
To ensure there are parenthesis you could simply add them:
text = "(" + text + ")"
Otherwise the suggested stack by Botz3000:
string text = "(paid for)";
Stack<int> parenthesis = new Stack<int>();
int last = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '(')
parenthesis.Push(i);
else if (text[i] == ')')
{
last = parenthesis.Pop();
}
}
if (last == 0)
{
// The matching parenthesis was the first letter.
}
You can check the right number of parenthesises by using something like a stack. Count up for each opening and count down for each closing brace. The same number of opening and closing braces means it matches. If you ever encounter a closing brace while your count is zero, that's a mismatch. If you want to know if your string is completely enclosed by paranthesises, check if all of them match, then check if your string starts with one.
static void BraceMatch(string text)
{
int level = 0;
foreach (char c in text)
{
if (c == '(')
{
// opening brace detected
level++;
}
if (c == ')')
{
level--;
if (level < 0)
{
// closing brace detected, without a corresponding opening brace
throw new ApplicationException("Opening brace missing.");
}
}
}
if (level > 0)
{
// more open than closing braces
throw new ApplicationException("Closing brace missing.");
}
}

check integrity of brackets in special formula

my program should print a message on the screen if the formula that the user entered is good for the terms(you can only use digits and letters, u can't start with '(' and like mathematical formula, for each open bracket, has to be a suitable(and in the right place) close bracket.
here some formulas that the program should accepts and prints:
True-
a(aa(a)aaa(aa(a)aa)aa)aaaaa
a(((())))
here some formulas that the program should not accepts and prints:
False-
()()()
)()()(
but the program always prints False
thanks for helping
Heres the code:EDIT
bool IsNumeric(char character)
{
return "0123456789".Contains(character);
// or return Char.IsNumber(character);
}
bool IsLetter(char character)
{
return "ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghigjklmnopqrstuvwxyz".Contains(character);
}
bool IsRecognized(char character)
{
return IsBracket(character) | IsNumeric(character) | IsLetter(character);
}
public bool IsValidInput(string input)
{
if (String.IsNullOrEmpty(input) || IsBracket(input[0]))
{
return false;
}
var bracketsCounter = 0;
for (var i = 0; i < input.Length; i++)
{
var character = input[i];
if (!IsRecognized(character))
{
return false;
}
if (IsBracket(character))
{
if (character == '(')
bracketsCounter++;
if (character == ')')
bracketsCounter--;
}
}
if (bracketsCounter > 0)
{
return false;
}
return bracketsCounter==0;
}
}
}
Your algorithm is unnecessarily complex - all you need is a loop and a counter.
Check the initial character for ( (you already do that)
Set the counter to zero, and go through each character one by one
If the character is not a letter or a parentheses, return false
If the character is an opening (, increment the counter
If the character is a closing ), decrement the counter; if the counter is less than zero, return false
Return true if the count is zero after the loop has ended; otherwise return false
Is debugging this hard really? This condition:
((!IsNumeric(st[i])) && (st[i] != '(') && (st[i] != ')')&&((st[i]<'a')||(st[i]>'z')||(st[i]<'A')||(st[i]>'Z')))
return false;
is obviously wrong. It returns false for a every time. You don't take into consideration that a is greater than Z.
EDIT:
so how can i make it easier to read? that the only way i figured. do u
have other solution for this problem?
As for that condition block - use smaller methods / functions, for example.
bool IsBracket(char character)
{
return (character == '(' | character == ')');
}
bool IsNumeric(char character)
{
return "0123456789".Contains(character);
// or return Char.IsNumber(character);
}
bool IsLetter(char character)
{
// see why this is NOT prone to fail just because 'a' is greater than 'Z' in C#?
return (character >= 'a' & character <= 'z') |
(character >= 'A' & character <= 'Z');
// or return Regex.IsMatch(character.ToString(), "[a-zA-Z]", RegexOptions.None);
// or return Char.IsLetter(character);
}
// now you can implement:
bool IsRecognized(char character)
{
return IsBracket(character) | IsNumeric(character) | IsLetter(character);
}
and then in your big method you could just safely use:
if (!IsRecognized(st[i]))
return false;
It may look like an overkill for such a trivial example, but it's a better approach in principle, and certainly more readable.
And after that, you could reduce your code to something along the lines of:
bool IsInputValid(string input)
{
if (String.IsNullOrEmpty(input) || IsBracket(input[0]))
{
return false;
}
var bracketsCounter = 0;
for (var i = 0; i < input.Length; i++)
{
var character = input[i];
if (!IsRecognized(character))
{
return false;
}
if (IsBracket(character)) // redundant?
{
if (character == '(') // then what?
if (character == ')') // then what?
}
if (bracketsCounter < what?)
{
what?
}
}
return bracketsCounter == what?;
}
(dasblinkenlight's algorithm)
EDIT 10th April
You got it wrong.
bool IsNumeric(char character)
{
return "0123456789".Contains(character);
// or return Char.IsNumber(character);
}
bool IsLetter(char character)
{
return "ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghigjklmnopqrstuvwxyz".Contains(character);
}
bool IsRecognized(char character)
{
return IsBracket(character) | IsNumeric(character) | IsLetter(character);
}
public bool IsValidInput(string input)
{
if (String.IsNullOrEmpty(input) || IsBracket(input[0]))
{
return false;
}
var bracketsCounter = 0;
for (var i = 0; i < input.Length; i++)
{
var character = input[i];
if (!IsRecognized(character))
{
return false;
}
if (IsBracket(character))
{
if (character == '(')
bracketsCounter++;
if (character == ')')
bracketsCounter--;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (bracketsCounter < 0) // NOT "> 0", and HERE - INSIDE the for loop
{
return false;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
return bracketsCounter==0;
}
}
}
By the way, you also made a mistake in your IsLetter method:
...UVWXWZ? Should be UVWXYZ

Parsing strings recursively

I am trying to extract information out of a string - a fortran formatting string to be specific. The string is formatted like:
F8.3, I5, 3(5X, 2(A20,F10.3)), 'XXX'
with formatting fields delimited by "," and formatting groups inside brackets, with the number in front of the brackets indicating how many consecutive times the formatting pattern is repeated. So, the string above expands to:
F8.3, I5, 5X, A20,F10.3, A20,F10.3, 5X, A20,F10.3, A20,F10.3, 5X, A20,F10.3, A20,F10.3, 'XXX'
I am trying to make something in C# that will expand a string that conforms to that pattern. I have started going about it with lots of switch and if statements, but am wondering if I am not going about it the wrong way?
I was basically wondering if some Regex wizzard thinks that Regular expressions can do this in one neat-fell swoop? I know nothing about regular expressions, but if this could solve my problem I am considering putting in some time to learn how to use them... on the other hand if regular expressions can't sort this out then I'd rather spend my time looking at another method.
This has to be doable with Regex :)
I've expanded my previous example and it test nicely with your example.
// regex to match the inner most patterns of n(X) and capture the values of n and X.
private static readonly Regex matcher = new Regex(#"(\d+)\(([^(]*?)\)", RegexOptions.None);
// create new string by repeating X n times, separated with ','
private static string Join(Match m)
{
var n = Convert.ToInt32(m.Groups[1].Value); // get value of n
var x = m.Groups[2].Value; // get value of X
return String.Join(",", Enumerable.Repeat(x, n));
}
// expand the string by recursively replacing the innermost values of n(X).
private static string Expand(string text)
{
var s = matcher.Replace(text, Join);
return (matcher.IsMatch(s)) ? Expand(s) : s;
}
// parse a string for occurenses of n(X) pattern and expand then.
// return the string as a tokenized array.
public static string[] Parse(string text)
{
// Check that the number of parantheses is even.
if (text.Sum(c => (c == '(' || c == ')') ? 1 : 0) % 2 == 1)
throw new ArgumentException("The string contains an odd number of parantheses.");
return Expand(text).Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
I would suggest using a recusive method like the example below( not tested ):
ResultData Parse(String value, ref Int32 index)
{
ResultData result = new ResultData();
Index startIndex = index; // Used to get substrings
while (index < value.Length)
{
Char current = value[index];
if (current == '(')
{
index++;
result.Add(Parse(value, ref index));
startIndex = index;
continue;
}
if (current == ')')
{
// Push last result
index++;
return result;
}
// Process all other chars here
}
// We can't find the closing bracket
throw new Exception("String is not valid");
}
You maybe need to modify some parts of the code, but this method have i used when writing a simple compiler. Although it's not completed, just a example.
Personally, I would suggest using a recursive function instead. Every time you hit an opening parenthesis, call the function again to parse that part. I'm not sure if you can use a regex to match a recursive data structure.
(Edit: Removed incorrect regex)
Ended up rewriting this today. It turns out that this can be done in one single method:
private static string ExpandBrackets(string Format)
{
int maxLevel = CountNesting(Format);
for (int currentLevel = maxLevel; currentLevel > 0; currentLevel--)
{
int level = 0;
int start = 0;
int end = 0;
for (int i = 0; i < Format.Length; i++)
{
char thisChar = Format[i];
switch (Format[i])
{
case '(':
level++;
if (level == currentLevel)
{
string group = string.Empty;
int repeat = 0;
/// Isolate the number of repeats if any
/// If there are 0 repeats the set to 1 so group will be replaced by itself with the brackets removed
for (int j = i - 1; j >= 0; j--)
{
char c = Format[j];
if (c == ',')
{
start = j + 1;
break;
}
if (char.IsDigit(c))
repeat = int.Parse(c + (repeat != 0 ? repeat.ToString() : string.Empty));
else
throw new Exception("Non-numeric character " + c + " found in front of the brackets");
}
if (repeat == 0)
repeat = 1;
/// Isolate the format group
/// Parse until the first closing bracket. Level is decremented as this effectively takes us down one level
for (int j = i + 1; j < Format.Length; j++)
{
char c = Format[j];
if (c == ')')
{
level--;
end = j;
break;
}
group += c;
}
/// Substitute the expanded group for the original group in the format string
/// If the group is empty then just remove it from the string
if (string.IsNullOrEmpty(group))
{
Format = Format.Remove(start - 1, end - start + 2);
i = start;
}
else
{
string repeatedGroup = RepeatString(group, repeat);
Format = Format.Remove(start, end - start + 1).Insert(start, repeatedGroup);
i = start + repeatedGroup.Length - 1;
}
}
break;
case ')':
level--;
break;
}
}
}
return Format;
}
CountNesting() returns the highest level of bracket nesting in the format statement, but could be passed in as a parameter to the method. RepeatString() just repeats a string the specified number of times and substitutes it for the bracketed group in the format string.

Categories