gpt4 book ai didi

c# - 如果 boolean 为 false,则在字符串中添加逗号和其他单词

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:16 26 4
gpt4 key购买 nike

我有 3 个 bool 值:

bool Boat, Plane, Car;

和 3 个字符串:

string ReloadBoat, ReloadPlane, ReloadCar;

根据这些 bool 值,如果为假,我需要在字符串之间添加逗号,并在最后两个字符串之间添加单词“and”。

string errorMessage = (Boat ? "" : " " + ReloadBoat + ", ") + (Plane ? "" : " " + ReloadPlane + ", ") + (Car ? "" : " " + ReloadCar);
errorMessage = errorMessage.TrimEnd(new[] { ' ', ',' });

对于上述内容,我遇到的问题是,如果 Boat 和 Plane 都为 false,我将收到错误消息“ReloadBoat,ReloadPlane”。

我希望它是“ReloadBoat 和 ReloadPlane”。

如果所有 3 个 bool 值都为 false,则 errorMessage 应为:ReloadBoat、ReloadPlane 和 ReloadCar。

最佳答案

您可以使用此解决方案(代码中的注释):

char comma = ',';

string errorMessage = (Boat ? "" : " " + ReloadBoat + comma) + (Plane ? "" : " " + ReloadPlane + comma) + (Car ? "" : " " + ReloadCar + comma);

// at first trim last comma
errorMessage = errorMessage.TrimEnd(comma);

// then replace the last separating comma with 'and'
int place = errorMessage .LastIndexOf(comma);
// only if comma is found
if(place >= 0)
errorMessage = errorMessage.Remove(place, 1).Insert(place, " and");

关于c# - 如果 boolean 为 false,则在字符串中添加逗号和其他单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56234686/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com