C# - Trimming string from first null terminator and onwards

纵然是瞬间 提交于 2020-01-06 17:56:05

问题


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.


回答1:


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);
}



回答2:


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'));



回答3:


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);


来源:https://stackoverflow.com/questions/1403524/c-sharp-trimming-string-from-first-null-terminator-and-onwards

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!