I need to know how I check the character in first position in a string on C# code. For example , if the first character is the character "&" or other.
Thanks.
从答案中可以看出,有很多方法可以做到这一点。string
如果您尝试在that is上调用方法或在that is或空null
上使用索引器,则应小心避免抛出异常。string
null
if(!String.IsNullOrEmpty(input) && input[0] == '&')
{
// yes
}
或者……</p>
if(input != null && input.StartsWith("&"))
{
// yes
}
不需要多次检查的最简单方法是使用String.CompareOrdinal重载。
string test = "&string";
if (String.CompareOrdinal(test, 0, "&", 0, 1) == 0) {
// String test started with &
}
这有一个额外的好处,即不需要检查 null 或空,因为静态方法会自动处理这些。
string test = "&myString";
if(!string.IsNullOrEmpty(test) && test[0] == '&')
{
// first character is &
}
尝试使用String.StartsWith方法。
if (MyString.StartsWith("&")) {
// do something.
}