DEV Community

Cover image for Detect a language from a string in C#.NET
Bug & Fix
Bug & Fix

Posted on

Detect a language from a string in C#.NET

Let's say you have a simple string in any language as your business forces you to let the client enter so you need to detect the language of the respected string at run time. We might have the varity of ways to solve solve this problem , but as a lazy .NET Developer, I am going to introduce a very simple Nuget tool to do job for you in less than a second.

First of all, create a simple Console Application in Visual Studio or in/by any IDE you want. Like below screen. 👇

Image description

Image description

then you would have a simple solution like what I have shared below. 👇

Image description

The next step is adding LanguageDetection.NETStandard Nuget package to the solution.

Image description

Image description

To make the long story short, just go through the simple piece of code that I have written.

Image description

As you can see, the result is not bad.

Image description

but if I try a different language ?. Something like Persian might be a little bit tricky!. Let's see.

Image description

Not bad !.

Since you guys are totally lazy to write even 3 lines of code, I do share the code with you below.

using LanguageDetection;

var LangDetector = new LanguageDetector();


LangDetector.AddAllLanguages();

//string MySimpleText = "This Text is a simple damn English string. Detect if you can!.";

string MySimpleText = "این یک متن فارسی ساده است. اگر مردی، این را تشخیص بده";


var Result=  LangDetector.Detect(MySimpleText);

Console.WriteLine(Result);
Enter fullscreen mode Exit fullscreen mode

That's all.

Enjoy C# development for ever...

Top comments (0)