我根据以下条件将一些字符串附加到我的字符串构建器对象:
StringBuilder Sb_Appearance = new StringBuilder();
if (Details.IsNeat == true)
Sb_Appearance.Append("Neat");
if (Details.IsDressed == true)
Sb_Appearance.Append(",Dressed");
if (Details.IsDisheveled == true)
Sb_Appearance.Append(",Disheveled");
if (Details.IsInappropriatelyDressed == true)
Sb_Appearance.Append(",Inappropriately Dressed");
if (Details.IsAppearanceOther == true)
Sb_Appearance.Append(",Other");
如果第一个和第四个条件出错,我的最终字符串可以变为::
,Dressed,Disheveled,Other
在这里我可以得到一个额外的逗号。我必须找到该逗号,如果它存在于第一个索引的Sb_Appearance中并且必须删除它。我怎么能这样做。
答案 0 :(得分:8)
我建议使用List<string>
并在之后加入:
var list = new List<string>();
if (Details.IsNeat)
list.Add("Neat");
if (Details.IsDressed)
list.Add("Dressed");
if (Details.IsDisheveled)
list.Add("Disheveled");
if (Details.IsInappropriatelyDressed)
list.Add("Inappropriately Dressed");
if (Details.IsAppearanceOther)
list.Add("Other");
var result = string.Join(", ", list);
我知道那不是你问的(你想要StringBuilder
)..但这就是你想要的。
答案 1 :(得分:2)
这是一种方式:
StringBuilder Sb_Appearance = new StringBuilder();
if (Details.IsNeat) Sb_Appearance.Append(",Neat");
if (Details.IsDressed) Sb_Appearance.Append(",Dressed");
if (Details.IsDisheveled) Sb_Appearance.Append(",Disheveled");
if (Details.IsInappropriatelyDressed) Sb_Appearance.Append(",Inappropriately Dressed");
if (Details.IsAppearanceOther) Sb_Appearance.Append(",Other");
var NewString = Sb_Appearance.ToString().TrimStart(',');
答案 2 :(得分:1)
您先添加逗号然后再添加值的原因是什么?如果可以,我会交换逗号。
StringBuilder Sb_Appearance = new StringBuilder();
if (Details.IsNeat == true)
Sb_Appearance.Append("Neat,");
if (Details.IsDressed == true)
Sb_Appearance.Append("Dressed,");
if (Details.IsDisheveled == true)
Sb_Appearance.Append("Disheveled,");
if (Details.IsInappropriatelyDressed == true)
Sb_Appearance.Append("Inappropriately Dressed,");
if (Details.IsAppearanceOther == true)
Sb_Appearance.Append("Other");
if(Sb_Appearance[Sb_Appearance.Length - 1] == ',')
Sb_Appearance.Remove(Sb_Appearance.Length - 1, 1);