Add one space after every two characters and add a character infront of every single character

后端 未结 4 766
甜味超标
甜味超标 2021-01-20 04:05

I want to add one space after every two characters, and add a character in front of every single character.

This is my code:

string str2;
str2 = str1         


        
相关标签:
4条回答
  • 2021-01-20 04:22

    Try something like this:

    static string ProcessString(string input)
    {
        StringBuilder buffer = new StringBuilder(input.Length*3/2);
        for (int i=0; i<input.Length; i++)
        {
            if ((i>0) & (i%2==0))
                buffer.Append(" ");
            buffer.Append(input[i]);
        }
        return buffer.ToString();
    }
    

    Naturally you'd need to add in some logic about the extra numbers, but the basic idea should be clear from the above.

    0 讨论(0)
  • 2021-01-20 04:24

    I think this is what you asked for

    string str1 = "3322356";
                string str2;
    
                str2 = String.Join(" ", 
                    str1.ToCharArray().Aggregate("",
                    (result, c) => result += ((!string.IsNullOrEmpty(result) &&
                        (result.Length + 1) % 3 == 0) ? " " : "") + c.ToString())
                        .Split(' ').ToList().Select(
                    x => x.Length == 1 
                        ? String.Format("{0}{1}", Int32.Parse(x) - 1, x) 
                        : x).ToArray());
    

    result is "33 22 35 56"

    0 讨论(0)
  • 2021-01-20 04:25
    [TestMethod]
    public void StackOverflowQuestion()
    {
        var input = "0123457";
        var temp = Regex.Replace(input, @"(.{2})", "$1 ");
        Assert.AreEqual("01 23 45 7", temp);
    }
    
    0 讨论(0)
  • 2021-01-20 04:29

    May be you can try, if i right understand your request,

    String.Length % 2
    

    if result is 0, you done with first iteration, if not, just add a character infront of last one.

    0 讨论(0)
提交回复
热议问题