After lot of googling, I finally found that char (or byte) arrays in C# do not have substring search. It has to be a String to do the same. It started with a sample code in MSDN for MemoryStream Class:
int count;
byte[] byteArray;
char[] charArray;
UnicodeEncoding uniEncoding = new UnicodeEncoding();
// Create the data to write to the stream.
byte[] firstString = uniEncoding.GetBytes(
"Invalid file path characters are: ");
byte[] secondString = uniEncoding.GetBytes(
Path.GetInvalidPathChars());
using (MemoryStream memStream = new MemoryStream(100))
{
// Write the first string to the stream.
memStream.Write(firstString, 0, firstString.Length);
// Write the second string to the stream, byte by byte.
count = 0;
while (count < secondString.Length)
{
memStream.WriteByte(secondString[count++]);
}
// Write the stream properties to the console.
Console.WriteLine(
"Capacity = {0}, Length = {1}, Position = {2}\n",
memStream.Capacity.ToString(),
memStream.Length.ToString(),
memStream.Position.ToString());
// Set the position to the beginning of the stream.
memStream.Seek(0, SeekOrigin.Begin);
// Read the first 20 bytes from the stream.
byteArray = new byte[memStream.Length];
count = memStream.Read(byteArray, 0, 20);
// Read the remaining bytes, byte by byte.
while (count < memStream.Length)
{
byteArray[count++] =
Convert.ToByte(memStream.ReadByte());
}
// Decode the byte array into a char array
// and write it to the console.
int charCnt = uniEncoding.GetCharCount(
byteArray, 0, count);
charArray = new char[charCnt];
uniEncoding.GetDecoder().GetChars(
byteArray, 0, count, charArray, 0);
Console.WriteLine(charArray);
}
Now this piece of code, when executed printed some non-printable chars. After debugging, found that Console.Writeline prints the whole array and does not stop when '\0' is found. Was trying to figure out if there is a way I can find the count of valid chars and pass it to WriteLine. The alternate solution I could think of is as below.Ofcourse a straight way (possibly more efficient) was to parse through the array and print but was curious to explore other ways :-)
String str = new String(charArray);
int strend = str.IndexOf('\0');
str = str.Remove(strend);
Console.WriteLine(str);
Comments
Post a Comment