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
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.
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"
[TestMethod]
public void StackOverflowQuestion()
{
var input = "0123457";
var temp = Regex.Replace(input, @"(.{2})", "$1 ");
Assert.AreEqual("01 23 45 7", temp);
}
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.