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

标签 c# string

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

例如:

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/

相关文章:

c# - ICollection<T> 上的 ElementAt(index)

c# - 使用 lambda 表达式选择两列

c# - 将整数传递给 VSTO 2010 Word 插件

python - python中的字符串转整数函数

java - 为什么链接 String.trim() 会抛出异常?

c# - 如何在 Expression Blend 2013 中获取 WPF 和 Windows Phone 模板?

c# - 如何使用Dapper获取存储过程的返回值?

php - MPRandomText 类的对象无法转换为字符串

java - 要检查是否将可解析的字符串传递给 Integer?

c# - 查找字符串中具有特定字母的所有单词