How to insert spaces between line characters

Is there an easy way to insert spaces between characters in a string? I use the code below that takes a string (e.g. (UI $ .EmployeeHours * UI.DailySalary) / (month)). Since this information comes from an excel sheet, I need to insert [] for each column name. This problem occurs if the user avoids providing spaces after each paranteza, as well as the operator. Anyone to help?

text = e.Expression.Split(Splitter); string expressionString = null; for (int temp = 0; temp < text.Length; temp++) { string str = null; str = text[temp]; if (str.Length != 1 && str != "") { expressionString = expressionString + "[" + text[temp].TrimEnd() + "]"; } else expressionString = expressionString + str; } 

The user can enter something like (UI $ .SlNo-UI + UI $ .Task) - (UI $ .Responsible_Person * UI $ .StartDate), while my desired result is ([UI $ .SlNo-UI] + [UI $ .Task]) - ([UI $ .Responsible_Person] * [UI $ .StartDate])

+3
source share
4 answers

Here is a short way to insert spaces after each individual character in a string (which I know is not what you requested):

 var withSpaces = withoutSpaces.Aggregate(string.Empty, (c, i) => c + i + ' '); 

This generates a line similar to the first, with the exception of a space after each character (including the last character).

+8
source

You can do this with regular expressions:

 using System.Text.RegularExpressions; class Program { static void Main() { string expression = "(UI$.SlNo-UI+UI$.Task)-(UI$.Responsible_Person*UI$.StartDate) "; string replaced = Regex.Replace(expression, @"([\w\$\.]+)", " [ $1 ] "); } } 

If you are not familiar with regular expressions, this may look rather cryptic, but they are a powerful tool and worth exploring. In the case, you can test how regular expressions work, and use a tool like Expresso to test your regular expressions.

Hope this helps ...

+3
source

Here is an algorithm that does not use regular expressions.

 //Applies dobule spacing between characters public static string DoubleSpace(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); char[] b = new char[ (a.Length * 2) - 1]; int bIndex = 0; for(int i = 0; i < a.Length; i++) { b[bIndex++] = a[i]; //Insert a white space after the char if(i < (a.Length - 1)) { b[bIndex++] = ' '; } } return new string(b); } 
+1
source

Well, you can do this using regular expressions, look for specific paterns and add parentheses where necessary. You can also simply replace each Paranthesis with the same Paranthesis, but with spaces at each end.

I would also advise you to use StringBuilder instead of adding to an existing string (this creates a new string for each manipulation, StringBuilder has less memory when doing this kind of manipulation)

0
source

All Articles