测试值字符串的第一个字符-C#

本文关键字:字符 -C# 第一个 字符串 测试 | 更新日期: 2023-09-27 18:27:43

在我们的一个报告打印模板中,有以下代码:

   if (!string.IsNullOrEmpty(assetModel.Belongings))
{
    description = string.Format("{0}{1}{2}",
        description,
        string.IsNullOrEmpty(description) ? "" : ", ",
        assetModel.Belongings);
}

我想测试"归属"字段的第一个字符。如果它不是","那么应该使用上面的代码,但如果它是","代码应该像:

   if (!string.IsNullOrEmpty(assetModel.Belongings))
{
    description = string.Format("{0}{1}{2}",
        description,
        string.IsNullOrEmpty(description) ? "" : "",
        assetModel.Belongings);
}

请帮忙,我如何测试第一个字符的值?

测试值字符串的第一个字符-C#

方法StartsWith是自我解释的:

if (description.StarstWith(","))
{
    //...
}

使用IndexOf检查,字符的索引是否为0,这意味着它位于字符串的开头。

if (description.IndexOf(',') == 0)
{
    // description starts with a ,
}