【问题标题】:Test value fist character of string - C# [duplicate]测试值字符串的第一个字符 - C# [重复]
【发布时间】:2016-03-27 06:01:22
【问题描述】:

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

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

我想测试 Belongings 字段的第一个字符。如果它不是“,”,那么应该使用上面的代码,但如果它是“,”,代码应该是这样的:

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

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

【问题讨论】:

标签: c# razor


【解决方案1】:

方法StartsWith不言自明:

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

【讨论】:

  • 谢谢,这是我一直在寻找的解决方案,这就是结果。抱歉,无法以正确的方式显示代码。 if (!string.IsNullOrEmpty(assetModel.Belongings)) {if (assetModel.Belongings.StartsWith(",")) { description = string.Format("{0}{1}{2}", description, string.IsNullOrEmpty (描述)?“”:“”,assetModel.Belongings); } else { description = string.Format("{0}{1}{2}", description, string.IsNullOrEmpty(description) ? "" : ", ",assetModel.Belongings); } }
【解决方案2】:

使用IndexOf检查,字符的索引是否为0,表示它在字符串的开头。

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

【讨论】:

  • 它应该可以工作,但 IndexOf 不是为此目的而构建的。在我看来,StartsWith() 在这种情况下会更好。
  • 搜索整个字符串而不是只检查description[0]==','?
  • @Jannik 是的,直到我发帖后才想到StartsWith
  • @Steve 我觉得你,我正要发布一个子字符串替代方案,嗯,有很多不同的道路可以达到同一个目标。
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
相关资源
最近更新 更多