-3

I am new to C# and trying to figure out how I could do this. So, what I am trying to do right now is to make a textbox out of text like this. If I have a sentence saying "Hello World. I have a problem. Can you help me?", I want to randomly pick one word and let the user fill it in. Could you please help me how to randomize the pick and make a textbox?

Thanks in advance for your help! :)

PS. I posted a pic for better understanding

Example picture of what I want to do

Kpan
  • 3
  • 1
  • See: [How to select a random element from a C# list?](https://www.tutorialspoint.com/how-to-select-a-random-element-from-a-chash-list) - [How to programmatically add controls to Windows forms at run time by using Visual C#](https://support.microsoft.com/en-us/help/319266/how-to-programmatically-add-controls-to-windows-forms-at-run-time-by-u) - [TextRenderer.MeasureText Method](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.textrenderer.measuretext?view=netframework-4.8). I let you put the pieces together. – Olivier Jacot-Descombes Jan 19 '20 at 16:57
  • [How do I (elegantly) transpose textbox over label at specific part of string?](https://stackoverflow.com/a/48615379/7444103) – Jimi Jan 19 '20 at 22:58

1 Answers1

0

Here is a way to get a random word of a sentence ...

You might split the sentence (tb.Text) into a string [] of words by using string.Split(' '). Then get a random number between '0' and .Length of your words. Then pick the random substring.

// split the string into substrings seperated by a blank ' ' ...
var strArrWords = tb.Text.Split(' ');
// get the number of words ...
var numWords = strArrWords.Length;
// get a random number between '0' and numWords-1
Random rnd = new Random();
var number = rnd.Next(0, numWords - 1);
// finally get your random word ...
var word =  tb.Text.Split(' ')[number];

or the same in 2 lines ...

Random rnd = new Random();
var word = tb.Text.Split(' ')[rnd.Next(0, tb.Text.Split(' ').Length - 1)];

To visualize this, you can maybee open another textbox displaying your word, the user can edit it. Then you replace the word in the other box, depends ...

I hope that helps :-)

tom2051
  • 82
  • 9
  • thanks so much! One more question please. What does the 'var' do? Can I replace it with string? – Kpan Jan 24 '20 at 07:44
  • in this case 'word' gets the return type of the function (tb.Split(...)[...] which is indeed 'string'. – tom2051 Jan 25 '20 at 09:35