我正在试着写一个程序,用户给系统一个单词和一个段落,系统的工作是计算这个单词出现的次数。
如何计算单词在C#中出现的次数?
发布于 2015-02-15 04:37:16
将正则表达式与Word Boundary锚点一起使用:
int wordCount = Regex.Matches(text, "\\b" + Regex.Escape(searchTerm) + "\\b", RegexOptions.IgnoreCase).Count;
发布于 2015-02-15 04:16:51
正如文章中所说的“There is a performance cost to the Split method. If the only operation on the string is to count the words, you should consider using the Matches or IndexOf methods instead
”
因此,如果性能有问题,您可以对indexOf使用while循环并进行计数。
class CountWords
{
static void Main()
{
string text = @"Historically, the world of data and the world of objects" +
@" have not been well integrated. Programmers work in C# or Visual Basic" +
@" and also in SQL or XQuery. On the one side are concepts such as classes," +
@" objects, fields, inheritance, and .NET Framework APIs. On the other side" +
@" are tables, columns, rows, nodes, and separate languages for dealing with" +
@" them. Data types often require translation between the two worlds; there are" +
@" different standard functions. Because the object world has no notion of query, a" +
@" query can only be represented as a string without compile-time type checking or" +
@" IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" +
@" objects in memory is often tedious and error-prone.";
string searchTerm = "data";
//Convert the string into an array of words
string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
// Create the query. Use ToLowerInvariant to match "data" and "Data"
var matchQuery = from word in source
where word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
select word;
// Count the matches, which executes the query.
int wordCount = matchQuery.Count();
Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCount, searchTerm);
// Keep console window open in debug mode
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
/* Output:
3 occurrences(s) of the search term "data" were found.
*/
发布于 2015-02-15 04:12:03
String test = "the full full :full? text !!! ";
String search = "full";
int count = String.Concat(test.Select(i => Char.IsPunctuation(i) ? ' ' : i))
.Split(' ').Where(i => i == search).Count();
这将:
通过检查每个字符( Count()
),
test.select
search
https://stackoverflow.com/questions/28519785
复制相似问题