如何统计特定符号的出现次数?

5

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

例如:

我狗的名字是 %x%,它今年 %y% 岁了。

可以被替换的单词位于 %% 之间。因此,我需要一个函数来告诉我在该字符串中有哪些变量。

GetVariablesNames(string) => result { %x%, %y% }
2个回答

7
我会使用正则表达式来查找任何看起来像变量的内容。
如果你的变量是百分号、任意字符、百分号,那么以下内容应该有效:
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:


谢谢您的回复。我从未使用过正则表达式,您能提供一些帮助来确定模式吗? - Darf Zon
值得注意的是,如果允许使用多个字符的变量(例如%myvar%),则模式将更改为“%\w*%”。 - Rob Ocel
@Takkara 感谢您指出这一点。我曾经考虑过,但忘记添加了。 - Jonathon Reinhart
1
使用模式%(\w*)%也会匹配零字符变量,即%% - Guffa
啊...我有点生疏了。修改为使用 +,它表示一个或多个。 - Jonathon Reinhart

1
你可以使用正则表达式获取出现次数,并将它们分组以计算每个出现次数。例如:
string text = "The name of my dog is %x% and he has %y% years old.";

Dictionary<string, int> keys =
  Regex.Matches(text, @"%(\w+)%")
  .Cast<Match>()
  .GroupBy(m => m.Groups[1].Value)
  .ToDictionary(g => g.Key, g => g.Count());

foreach (KeyValuePair<string,int> key in keys) {
  Console.WriteLine("{0} occurs {1} time(s).", key.Key, key.Value);
}

输出:

x occurs 1 time(s).
y occurs 1 time(s).

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接