gpt4 book ai didi

C#:匹配字符串中的确切单词

转载 作者:太空宇宙 更新时间:2023-11-03 21:06:01 27 4
gpt4 key购买 nike

我有一个包含键值对的字符串,例如“this:1 is:2 a:3 Bigtest:4 and:5 i:6 want:7 to:8 pass:9 in:10 this:11 test:12和:13 字符串:14 继续:15"

现在我想从此字符串中提取标签(比如测试)的值。我无法提取标签测试的值 12,因为我编写的匹配逻辑匹配选项卡 Bigtest 并给出输出为 4。

我是 C# 的新手,所以在这方面需要一些专家帮助。

我的逻辑:消息是包含键值的字符串,属性是标签名称(测试)

public static string GetAttributeValueByName(string message, string attributeName)
{
int startIndex = message.IndexOf(attributeName + ":");

string attribute = message.Substring(startIndex + (attributeName + "=").Length);

int position = attribute.IndexOf(' ', 1);


if (position != -1)
{
string attributeValue = attribute.Substring(1, position - 1);
return attributeValue;
}

return "";
}

提前致谢。

最佳答案

如果您首先在空格处拆分字符串:

var pairs = input.Split(" ");

你最终会得到这样的数组:

this:1
is:2
a:3
Bigtest:4
and:5
i:6
want:7
to:8
pass:9
in:10
this:11
test:12
and:13
string:14
continues:15

然后您可以循环遍历数组中以冒号分隔的每个元素,并检查该对中的第一个元素是否与您的测试词匹配。

字符串输出; foreach(变量对成对) { var result = pair.Split(":"); 如果(结果[0] == testWord) { 输出=结果[1]; 休息; }

显然,您需要进行错误捕获和输入验证。

关于C#:匹配字符串中的确切单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41089028/

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