Reputation: 5177
its a simple code to split a byte array and see how it works. But the problem is I get weird outputs.
public static void SplitArayUsingLinq()
{
int i = 3;
string data = "123456789";
byte[] largeBytes = Encoding .Unicode .GetBytes (data);
byte[] first = largeBytes.Take(i).ToArray();
byte[] second = largeBytes.Skip(i).ToArray();
string firststring = Encoding.Unicode .GetString (first);
string secondstring = Encoding.Unicode.GetString(second);
Console.WriteLine(" first : " +firststring);
Console.WriteLine(" second : " +secondstring);
}
when the value of i=3 I get this:
and when the value of i=4 I get this:
In both cases I get weird outputs. It seems that whatever the value of i is given, the program seems to consider its half. Can anyone tell me why is it happening? exactly where is the problem?
Upvotes: 1
Views: 481
Reputation: 5177
I just changed the Unicode to UTF8 and the problem is solved. Thanks everyone who answered and commented.
UPDATE:
the correct code is :
public static void SplitArayUsingLinq()
{
int i = 3;
string data = "123456789";
byte[] largeBytes = Encoding.UTF8.GetBytes (data);
byte[] first = largeBytes.Take(i).ToArray();
byte[] second = largeBytes.Skip(i).ToArray();
string firststring = Encoding.UTF8.GetString (first);
string secondstring = Encoding.UTF8.GetString(second);
Console.WriteLine(" first : " +firststring);
Console.WriteLine(" second : " +secondstring);
}
Upvotes: 0
Reputation: 127543
Unicode uses two bytes per character, so only even values of i
will work and it will take half the number of letters. If you just want to split a string doing String.SubString
will be a lot easier.
int i = 3;
string data = "123456789";
string firststring = data.SubString(0,i);
string secondstring = data.SubString(i+1);
Console.WriteLine(" first : " +firststring);
Console.WriteLine(" second : " +secondstring);
Upvotes: 4