gpt4 book ai didi

c# - 如何统计某些符号出现的次数?

转载 作者:太空狗 更新时间:2023-10-29 22:52:45 27 4
gpt4 key购买 nike

在我的程序中,你可以写一个字符串,你可以在其中写变量。

例如:

The name of my dog is %x% and he has %y% years old.

我可以替换的单词是 %% 之间的任何一个。所以我需要一个函数来告诉我在那个字符串中有哪些变量。

GetVariablesNames(string) => result { %x%, %y% }

最佳答案

我会使用 Regular Expression找到任何看起来像变量的东西。

如果您的变量是百分号、任何单词字符、百分号,那么以下应该有效:

string input = "The name of my dog is %x% and he has %y% years old.";

// The Regex pattern: \w means "any word character", eq. to [A-Za-z0-9_]
// We use parenthesis to identify a "group" in the pattern.

string pattern = "%(\w)%"; // One-character variables
//string pattern ="%(\w+)%"; // one-or-more-character variables

// returns an IEnumerable
var matches = Regex.Matches(input, pattern);

foreach (Match m in matches) {
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
var variableName = m.Groups[1].Value;
}

MSDN:

关于c# - 如何统计某些符号出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13788793/

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