gpt4 book ai didi

c# - 如果我的变量中包含 "n+1"数字,如何获取 "n"作为输出?

转载 作者:行者123 更新时间:2023-11-30 20:33:51 27 4
gpt4 key购买 nike

我有一个包含以下数据的字符串变量。

string str = string.Empty;
if ("my condition")
{
str = list[i] + Environment.NewLine;
}

其中 i 是文本文件中的行数,

list[0]="Step 1:Some text"
list[1]="continuation of the text in step1"
list[2]="Step 2:Some text"
list[3]="continuation of the text in step2"
list[4]="Step 3:Some text"
list[5]="continuation of the text in step3"

当我打印 str 变量时,我得到了所有步骤。除此之外,我还必须向其附加一条消息。我正在使用以下控制台代码,

string error = str + Environment.NewLine + "Step 4:Some text";

现在不是直接使用Step 4:,而是有什么方法可以计算 Steps 的数量并生成下一个数字并将其存储在变量中吗?将在这种情况下使用Split() 函数。

最佳答案

您可以使用 Linq:

var stepCount = list.Count(text => text.StartsWith("Step")) + 1;
//C#6
var error = $"{str}{Environment.NewLine}Step {stepCount.ToString()}:Some text";
//Or C# before version 6
var error = string.Format("{0}{1}Step {2}:Some text", str, Environment.NewLine, stepCount.ToString());
//Or use StringBuilder
var error = new StringBuilder().AppendLine(str).Append("Step ")
.Append(stepCount.ToString()).Append(":SomeText").ToString();
//Or plain old string concat
var error = str + Environment.NewLine + "Step " + stepCount.ToString() + ":Some text";

关于c# - 如果我的变量中包含 "n+1"数字,如何获取 "n"作为输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39850873/

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