Skip to content

Instantly share code, notes, and snippets.

@evilmucedin
Last active August 30, 2016 09:26
Show Gist options
  • Save evilmucedin/af111923bba89bfe9ce2d5999111cefd to your computer and use it in GitHub Desktop.
Save evilmucedin/af111923bba89bfe9ce2d5999111cefd to your computer and use it in GitHub Desktop.
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