views:

151

answers:

3

I have a C# string "RIP-1234-STOP\0\0\0\b\0\0\0???|B?Mp?\0\0\0" returned from a call to a native driver.

How can I trim all characters from first null terminator '\0\ onwards. In this case, I just would like to have "RIP-1234-STOP".

Thanks.

+3  A: 

Try this:

var input = "RIP-1234-STOP\0\0\0\b\0\0\0???|B?Mp?\0\0\0";
var firstNull = input.IndexOf('\0');
var output = input.Substring(0, firstNull);

or simply:

var output = input.Substring(0, input.IndexOf('\0'));
Luke Quinane
Of course, if '\0' is not found, this solution will throw an ArgumentOutOfRangeException.
RKitson
A: 

This works too:

var input = "RIP-1234-STOP\0\0\0\b\0\0\0???|B?Mp?\0\0\0";
var split = input.Split('\0');
var output = split[0];
Assert.AreEqual("RIP-1234-STOP", output);
RKitson
+8  A: 

Here is a method that should do the trick

string TrimFromZero(string input)
{
  int index= input.IndexOf('\0');
  if(index < 0)
    return input;

  return input.Substring(0,index);
}
aaronb
+1 for being the only answer that doesn't overuse the var keyword.
Guffa
heh, so true...
Philippe
Good method for sure. Have a hard time believing that it would be ANY less readable with a 'var' instead of the 'int'.
RKitson