Behavior Behavior -3 years ago 164
C# Question

C#: Replace random letters with letters from another keyboard layout

Sorry for my bad english. So, i have a code.

public Random rnd = new Random();

public string RandomizeLetters(string text)
{
string variations = "";

foreach (var letter in text)
{
var а = new List<string> { "а", "аa" };
var е = new List<string> { "е", "еe" };
var о = new List<string> { "о", "оo" };
var р = new List<string> { "р", "рp" };
var с = new List<string> { "с", "сc" };
var у = new List<string> { "у", "уy" };
var х = new List<string> { "х", "хx" };

var alphavite = new List<List<string>> { а, е, о, р, с, у, х };

var res = new StringBuilder();

foreach (var x in alphavite)
{
if (x.Exists(e => e.EndsWith(letter.ToString())))
{
res.Append(x[1][rnd.Next(0, x[1].Length)]);
}
}

res.Append(letter.ToString());

variations += res;
}

return variations.ToString();
}


This code replaces random letters with letters that are visually similar to letters from a different keyboard layout, in my case, from Russian keyboard layout to the English keyboard layout.
But instead of the desired result, I get text with duplicate characters.

Here is the text I want to process:


Для проверки наличия в вашем тексте символов из другого языка - скопируйте исходный текст, вставьте его в поле ниже, и выберите нужный чекбокс языка


But the text that I get at the output:


Для пpроовeеpрки нaаличия в ваашeем теекcстeе cсимвоолоов из дрруугоогоо языкaа - сскоопиpрууйтее иcсxхoодный теекcст, всстaавьтее eегoо в поолeе нижее, и выбeеpритeе нyужный чеекбоокcс языкаа


How to fix it? I check the text with the help of the service for checking the characters: raskladka.obmen-service.com

Answer Source

Even if you replace letter with res.Append(x[1][rnd.Next(0, x[1].Length)]); later you still append base letter: res.Append(letter.ToString()); Try adding a condition:

        bool replaced = false;
        foreach (var x in alphavite)
        {
            if (x.Exists(e => e.EndsWith(letter.ToString())))
            {
                res.Append(x[1][rnd.Next(0, x[1].Length)]);
                replaced = true;
            }
        }
        if(!replaced)
            res.Append(letter.ToString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download