Add one space after each two characters and add infront character for each individual character

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

This is my code:

string str2;
str2 = str1.ToCharArray().Aggregate("", (result, c) => result += ((!string.IsNullOrEmpty(result) && (result.Length + 1) % 3 == 0) ? " " : "") + c.ToString());

I have no problem dividing every two characters with one space, but how do I know if the selected text has a separate character and adds the infront character to that character?

I understand that my question is confused because I am not sure how to put what I want in words. So I’ll just give an example:

I have this line:

0123457

Separating every two characters with a space, I get:

01 23 45 7

I want to add 6 infront of 7.

Note. Numbers depend on user input, so it is not always the same.

Thank.

+3
source share
4 answers

, ,

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());

"33 22 35 56"

+1
[TestMethod]
public void StackOverflowQuestion()
{
    var input = "0123457";
    var temp = Regex.Replace(input, @"(.{2})", "$1 ");
    Assert.AreEqual("01 23 45 7", temp);
}
+20

- :

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 need to add some logic about additional numbers, but the main idea should be clear from the above.

+4
source

Maybe you can try, if I understand your request correctly,

String.Length % 2

If the result is 0, you did with the first iteration, if not, just add the infront character to the last.

+2
source

All Articles