Last active
August 30, 2016 09:26
-
-
Save evilmucedin/af111923bba89bfe9ce2d5999111cefd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class Spaces { | |
public static void Main(string[] args) { | |
var s = "12345678"; | |
var r = InjectSpaces(s); // r == "1 2 3 4" | |
for (int i = 0; i < 200000000; ++i) { | |
r = InjectSpaces(s); | |
} | |
Console.WriteLine("'{0}' -> '{1}'", s, r); | |
} | |
static unsafe string InjectSpaces(string s) { | |
fixed (char* pS = s) { | |
var pLength = (int*)pS - 1; | |
var length = *pLength & 0x3fffffff; | |
var result = new string(' ', 2*length - 1); | |
fixed (char* pResult = result) { | |
for (int i = 0; i < length; ++i) { | |
pResult[2*i] = pS[i]; | |
} | |
} | |
return result; | |
} | |
} | |
static string InjectSpaces2(string s) { | |
var ra = new char[s.Length * 2 - 1]; | |
ra[0] = s[0]; | |
for (int i = 1; i < s.Length; ++i) { | |
ra[2*i - 1] = ' '; | |
ra[2*i] = s[i]; | |
} | |
return new string (ra); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment