How to insert spaces between the characters of a string

后端 未结 4 578
醉酒成梦
醉酒成梦 2021-01-14 08:01

Is there an easy method to insert spaces between the characters of a string? I\'m using the below code which takes a string (for example ( UI$.EmployeeHours * UI.DailySalar

相关标签:
4条回答
  • 2021-01-14 08:34

    Well, you can do this by using Regular expressions, search for specific paterns and add brackets where needed. You could also simply Replace every Paranthesis with the same Paranthesis but with spaces on each end.

    I would also advice you to use StringBuilder aswell instead of appending to an existing string (this creates a new string for each manipulation, StringBuilder has a smaller memory footprint when doing this kind of manipulation)

    0 讨论(0)
  • 2021-01-14 08:35

    Here is a short way to insert spaces after every single character in a string (which I know isn't exactly what you were asking for):

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

    This generates a string the same as the first, except with a space after each character (including the last character).

    0 讨论(0)
  • 2021-01-14 08:38

    You can do that 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 might look rather cryptic, but they are a powerful tool, and worth learning. In case, you may check how regular expressions work, and use a tool like Expresso to test your regular expressions.

    Hope this helps...

    0 讨论(0)
  • 2021-01-14 08:47

    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);
    }
    
    0 讨论(0)
提交回复
热议问题