king jia
king jia

Reputation: 712

Convert from byte array to string and Split String

Let's say I have a byte array

Byte[] arr;

Then I will convert the array to string 1st.

String inputString = "";
foreach (Byte b in arr)
{
   if (b != 0)
      inputString += (Char) b;
   else inputString += " ";
}

Let's say the string is:

inputString  = @"C:\Program Files\Test C:\Users\User A\AppData\Local\Temp C 32323 C:\Program Files\Test\Temp";

I want it to be split into 4 strings that look like below:

C:\Program Files\Test \\position 0 = test folder
C:\Users\User A\AppData\Local\Temp \\position 1 = windows temp folder
C 32323 \\position 2 = a name. It can be C2313 or C 2312 or whatever string
C:\Program Files\Test\Temp \\position 3 = temp for test folder
\\ position can change by me...

every string in between will be split by space. That's mean I can use .Split(' '). However, as you know some of the path has space in between, 'C:\Program Files\Test' is an example.

How can I get the values I want?

Upvotes: 0

Views: 631

Answers (2)

king jia
king jia

Reputation: 712

Here is my answer. Thanks @xanatos for the advise.

String inputString = "";
bool isRepeat = false;
foreach (Byte b in arr)
{
   if (b != 0)
   {
      inputString += (Char)b;
      isRepeat = false;
   }
   else
   {
      if (!isRepeat)
      {
         inputString += "|";
         isRepeat = true;
      }
   }               
}

Upvotes: 0

xanatos
xanatos

Reputation: 111850

Try doing this:

byte[] arr = ...

string[] inputStrings = Encoding.GetEncoding("iso-8859-1").GetString(arr).Split('\0');

And see the result.

Upvotes: 1

Related Questions