Created
September 29, 2016 01:12
-
-
Save htsign/2734deaa61f84051546e75d5f1cdab15 to your computer and use it in GitHub Desktop.
文字列の 2, 7, 12, 17, 22 文字目をアンマネージメモリ上で変更して新たに文字列を作成する
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; | |
using System.Runtime.InteropServices; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string str = "ABCDEabcde01234ひらがなカタカナ漢字", newstr1, newstr2; | |
IntPtr ptr = Marshal.StringToHGlobalUni(str); | |
Marshal.WriteInt16(IntPtr.Add(ptr, sizeof(short) * 2), (short)'-'); | |
Marshal.WriteInt16(IntPtr.Add(ptr, sizeof(short) * 7), (short)'-'); | |
Marshal.WriteInt16(IntPtr.Add(ptr, sizeof(short) * 12), (short)'-'); | |
Marshal.WriteInt16(IntPtr.Add(ptr, sizeof(short) * 17), (short)'-'); | |
Marshal.WriteInt16(IntPtr.Add(ptr, sizeof(short) * 22), (short)'-'); | |
newstr1 = Marshal.PtrToStringUni(ptr); | |
Marshal.FreeHGlobal(ptr); | |
unsafe | |
{ | |
fixed (char* p = str.ToCharArray()) | |
{ | |
p[ 2] = '-'; | |
p[ 7] = '-'; | |
p[12] = '-'; | |
p[17] = '-'; | |
p[22] = '-'; | |
newstr2 = new string(p); | |
} | |
} | |
Console.WriteLine(str); | |
Console.WriteLine(newstr1); | |
Console.WriteLine(newstr2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment