E
E
estry2018-08-18 09:24:51
C++ / C#
estry, 2018-08-18 09:24:51

How to add characters to a string?

Hello. Tell me how to insert a random number of required characters into a string in random places.
For example.
String - 123456789qwerty
Symbols - _ ' * ~ - | \ /
Expected result is 1'23**45_678~~9qw|er\t//y
Thanks for your help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
CrazyElf, 2018-08-18
@estry

Some long code for estry. I got this one:

string str = "123456789qwerty";
string sym = @"_'*~-|\/";
string res = "";
var prob = 0.3;
Random rnd = new Random();
bool first = true;
foreach(var ch in str)
{
    if (!first)
    {
        var rch = sym[rnd.Next(0, sym.Length - 1)];
        while(rnd.NextDouble() < prob)
        {
            res += rch;
        }
    }
    first = false;
    res += ch;
}
Console.WriteLine(res);
Console.ReadLine();

PS This is provided that we insert characters only inside the string, we do not insert before the first and after the last character. If you need it differently, then you will need to redo it a little.

K
Keste ..., 2018-08-18
@Keste

Take a string into an array and characters into another array, then determine the positions of the characters in the first array and, using random, determine where to add (do not forget: do not replace, but add), insert characters into the first array and output it.
Seems pretty simple...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question