/ Published in: C#
Double-null-terminated strings are sometimes referred to as multistrings - \r\nhttp://stackoverflow.com/questions/268899/how-do-you-convert-multistring-to-from-c-string-collection\r\n\r\nmultistrings used in...\r\nOPENFILENAME::lpstrFilter in common dialogs\r\nRegQueryStringValue\r\nChangeServiceConfig\r\n\r\nThis works somewhat...\r\nstring[] a2 = (new string(Buff)).TrimEnd(\'\\0\').Split(\'\\0\');\r\n...but includes junk after a double-null.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/// <summary> /// Convert a double-null terminated string into an array of strings /// Example usage: /// char [] buff = new char[]; /// // fill Buff with data calling an API. /// string[] a = MultistringToStringArray(ref buff); // Find first double-null. /// </summary> /// <param name="arg">double-null terminated string</param> /// <returns>array of strings</returns> /// Gracefully handle fringe conditions: missing double-null, missing trailing single null, private static string [] MultistringToStringArray(ref char[] arg) { // Search an array of bytes for a double-null before converting to string. int qty, j; for ( qty = 0, j = 1; ; qty++, j++) { bool done = qty > (arg.Length - 1) || (arg[qty] == 0 && j < arg.Length && arg[j] == 0); if (done) { break; } // if } // for } // lengthDoubleNull // More concise but less efficient variation. private static string [] MultistringToStringArray(ref char[] arg) { int x = s2.IndexOf("\0\0"); // find double-null. if (x != -1) { s2 = s2.Remove(x); } // remove if found. } // test this function. Use Enumerable.SequenceEqual to deep-compare array of strings. [Conditional("DEBUG")] private static void MultistringToStringArrayTest() { char[] b; // fringe scenario. missing double-null. // fringe scenario. missing double-null. // fringe scenario. missing single-null. // Most common scenario - embedded nulls with a terminating double-null and junk after that. Debug.Assert( Enumerable.SequenceEqual(new string[] { "abc", "123" }, MultistringToStringArray(ref b))); // fringe scenario. missing double-null. Debug.Assert(Enumerable.SequenceEqual(new string[] { "abc", "1234" }, MultistringToStringArray(ref b))); // common scenario. Debug.Assert(Enumerable.SequenceEqual(new string[] { "abc", "1234", "ABC" }, MultistringToStringArray(ref b))); }