gpt4 book ai didi

c# - 用列表条目替换字符串出现

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:09 25 4
gpt4 key购买 nike

我一直在绞尽脑汁想找到一个“优雅”的解决方案,但我对它不太满意。

可能的输入字符串:

foo () bar ()

() bar

foo

()()foo () bar

括号之间可以有“无限”的括号和可选的非括号文本。这些空括号的内容应该用取自 List<string> 的数据填充。按照列表条目的顺序。如果没有条目或条目不足,则括号保持不变。

可能的字符串替换:

foo () bar ()替换为 x, y将导致 foo (x) bar (y)

foo () bar ()替换为 x将导致 foo (x) bar ()

foo () bar ()替换为 x, y, z将导致 foo (x) bar (y)

我希望你明白这一点。

解决方案:到目前为止,我的解决方案是摆弄索引和许多特殊逻辑来处理不同的情况。

我想知道是否有更优雅的解决方案,例如正则表达式。也许我现在离这个问题太近了,有一个简单的解决方案:-)

这是一种我不太满意的方法(可读性/易于理解):

  var guiIdentifierIndex = 0;
var guiIdentifierList = new List<string>{"x", "y", "z", "x", "y"};

var sourcePathItem = "foo ()";
string targetString = "";
var splittedPath = sourcePathItem.Split(new string[] { BRACKETS }, StringSplitOptions.None);
for (int index = 0; index < splittedPath.Length; index++)
{
var subPath = splittedPath[index];
var guiIdentifier = string.Empty;
if (guiIdentifierIndex < guiIdentifierList.Count)
{
guiIdentifier = guiIdentifierList[guiIdentifierIndex];
guiIdentifierIndex++;
}
targetString += subPath;
if (index < splittedPath.Length - 1)
targetString += string.Format("({0})", guiIdentifier);
}

http://volatileread.com/utilitylibrary/snippetcompiler?id=22718

最佳答案

您可以使用正则表达式,例如

  String source = "foo () bar ()";

var guiIdentifierList = new List<String> {
"x", "y", "z", "x", "y" };

int guiIdentifierIndex = 0;

// result == "foo (x) bar (y)"
String result = Regex.Replace(source, @"\(\)", (MatchEvaluator) (
(match) => "(" + (guiIdentifierIndex < guiIdentifierList.Count
? guiIdentifierList[guiIdentifierIndex++]
: "") + ")"
));

关于c# - 用列表条目替换字符串出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31452556/

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