Reputation: 6575
I was Trying to Implement Substring on my own just for practice.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Substring
{
public Substring()
{
string test = "giladdarmonwhatareyoudoing";
string res = ApplySubString(5, test);
string res2 = ApplySubString2(5, test);
}
public string ApplySubString(int i, string test)
{
char[] charArray = test.ToArray();
StringBuilder sb = new StringBuilder();
for (; i < charArray.Length; i++)
{
sb.Append(charArray[i]);
}
return sb.ToString();
}
public string ApplySubString2(int i, string test)
{
char[] charArray = new char[test.Length - i];
Buffer.BlockCopy(test.ToCharArray(), i, charArray, 0, test.Length - i);
return new String(charArray);
}
}
}
so the output from ApplySubString() is as expected.
however the output from ApplySubString2 is
[0]: 24832 '愀'
[1]: 25600 '搀'
[2]: 25600 '搀'
[3]: 24832 '愀'
[4]: 29184 '爀'
[5]: 27904 '洀'
[6]: 28416 '漀'
[7]: 28160 '渀'
[8]: 30464 '眀'
[9]: 26624 '栀'
[10]: 0 '\0'
[11]: 0 '\0'
[12]: 0 '\0'
[13]: 0 '\0'
[14]: 0 '\0'
[15]: 0 '\0'
[16]: 0 '\0'
[17]: 0 '\0'
[18]: 0 '\0'
[19]: 0 '\0'
[20]: 0 '\0'
Can someone please explain why ? and what is my mistake?
Upvotes: 1
Views: 784
Reputation: 941317
This turns into Chinese because i
is an odd number. You are in effect swapping the low and high bytes in the characters because you start copying in the middle of a char. Note that Buffer.BlockCopy()
requires using the byte offset and length, not the element offset/length. You therefore have to multiply by sizeof(char). Or 2. Fix:
public string ApplySubString2(int i, string test) {
char[] charArray = new char[test.Length - i];
Buffer.BlockCopy(test.ToCharArray(), i * sizeof(char),
charArray, 0, (test.Length - i) * sizeof(char));
return new String(charArray);
}
Upvotes: 4
Reputation: 6575
Like SLaks said Buffer.BlockCopy deals with bytes, so here is the new implementation
public string ApplySubString2(int i, string test)
{
char[] charArray = new char[test.Length - i];
Array.Copy(test.ToCharArray(), i, charArray, 0, test.Length - i);
return new String(charArray);
}
Upvotes: 1