using System.Diagnostics;
using System.Text.RegularExpressions;
public static void Main()
private static void InsertSpaces1()
Stopwatch w = new Stopwatch();
string text = " ( ((abc ) def)ghi)";
text = Regex.Replace(text.Replace("(", " ( ").Replace(")", " ) "), @"[ ]{2,}", @" ");
Console.WriteLine(w.Elapsed);
private static void InsertSpaces2()
Stopwatch w = new Stopwatch();
string text = " ( ((abc ) def )ghi)";
text = Regex.Replace(text.Replace(" ", String.Empty), "\\w+|[()]", "$0 ");
Console.WriteLine(w.Elapsed);
private static void InsertSpaces3()
Stopwatch w = new Stopwatch();
StringBuilder text = new StringBuilder("( ((abc ) def )ghi)");
for (int i = 0; i < text.Length; i++)
(text[i] == '(' && ((i - 1 >= 0 && text[i - 1] != ' ') || i == 0)) ||
(text[i] == ')' && ((i - 1 >= 0 && text[i - 1] != ' ') || i == 0))
(text[i] == '(' && (i + 1 < text.Length && text[i + 1] != ' ')) ||
(text[i] == ')' && (i + 1 < text.Length && text[i + 1] != ' '))
(text[i] == '(' && (i + 1 == text.Length)) ||
(text[i] == ')' && (i + 1 == text.Length))
Console.WriteLine(w.Elapsed);
private static void InsertSpaces4()
Stopwatch w = new Stopwatch();
string text = "( ((abc ) def )ghi)";
for (int i = 0; i < text.Length; i++)
(text[i] == '(' && ((i - 1 >= 0 && text[i - 1] != ' ') || i == 0)) ||
(text[i] == ')' && ((i - 1 >= 0 && text[i - 1] != ' ') || i == 0))
text = text.Insert(i, " ");
(text[i] == '(' && (i + 1 < text.Length && text[i + 1] != ' ')) ||
(text[i] == ')' && (i + 1 < text.Length && text[i + 1] != ' '))
text = text.Insert(i + 1, " ");
(text[i] == '(' && (i + 1 == text.Length)) ||
(text[i] == ')' && (i + 1 == text.Length))
Console.WriteLine(w.Elapsed);