DEV Community

Frederik Van Lierde
Frederik Van Lierde

Posted on

2

Calculating Article Reading Time in .Net

Letting your readers know how much time it takes to read your content helps improve user experience.

I saw many articles by people, that use string.split to count the words. The problem I have with string.split is that it will create (immutable) strings for every word, and that is heavy on the garbage collector, certainly when you have a long-form article.

Count Words (up to .net6)

public static int CountWords(this string str)
{
  return Regex.Matches(str, @"[\w-]+").Count();
}
Enter fullscreen mode Exit fullscreen mode

Count Words (.net7)

public static int CountWords(this string str)
{
  return Regex.Count(str, @"[\w-]+");
}
Enter fullscreen mode Exit fullscreen mode

Calculate the reading Time

Most people can read between 200 and 250 words per minute
The easiest way to calculate is to divide the number of words by the speed.

public static int CountMinutesRead(this string str)
{
  return Convert.ToInt32(str.CountWords() / 228);
}
Enter fullscreen mode Exit fullscreen mode

These functions will be added to the CodeHelper.Core.Extensions packages soon!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay