-1

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.

4

4 回答 4

3

从答案中可以看出,有很多方法可以做到这一点。string如果您尝试在that is上调用方法或在that is或空null上使用索引器,则应小心避免抛出异常。stringnull

if(!String.IsNullOrEmpty(input) && input[0] == '&')
{
    // yes
}

或者……</p>

if(input != null && input.StartsWith("&"))
{
    // yes
}
于 2013-05-08T16:47:05.483 回答
2

不需要多次检查的最简单方法是使用String.CompareOrdinal重载。

string test = "&string";
if (String.CompareOrdinal(test, 0, "&", 0, 1) == 0) {
  // String test started with &
}

这有一个额外的好处,即不需要检查 null 或空,因为静态方法会自动处理这些。

于 2013-05-08T16:51:22.733 回答
1
string test = "&myString";
if(!string.IsNullOrEmpty(test) && test[0] == '&')
{
    // first character is &
}
于 2013-05-08T16:45:58.047 回答
0

尝试使用String.StartsWith方法。

if (MyString.StartsWith("&")) {
    // do something.
}
于 2013-05-08T16:47:41.493 回答