0

How do I convert the result of:

Random rnd = new Random();
var x = rnd.Next(1,4);

if x is 1 I just need it to be '1', if it is 2 I just need it to be '2', and if it is 3 I just need it to be '3'. Basically just add the quotation marks. Thank you.

4
  • you could type cast like (string)rnd.Next(1,4); or do a rnd.Next(1,4).toString(); Commented May 22, 2019 at 11:53
  • @PrashanthBenny that (string)rnd.Next would not work Commented May 22, 2019 at 11:55
  • Possible duplicate of Convert int to string? Commented May 22, 2019 at 12:07
  • 1
    @Hans Passant I need '1' not "1" Sir. Commented May 22, 2019 at 12:21

6 Answers 6

2

There are several ways to do it, here are a couple of them:

Add the char zero (only works if it's one digit):

var c = (char)('0' + rnd.Next(1,4));

Convert to string and get the first character:

var c = rnd.Next(1, 4).ToString().ToCharArray()[0];
Sign up to request clarification or add additional context in comments.

Comments

1

You could convert to string :

var x = rnd.Next(1, 4).ToString()[0]

2 Comments

Why ToCharArray(), when string has indexer?
You can directly access a string character: rnd.Next(1, 4).ToString()[0];
0

You can add this number to the char '0' to get the char value.

Random rnd = new Random();
var x = rnd.Next(1,4);
char c = Convert.ToChar(x + '0');
Console.WriteLine("x : " + x + " - c : " + c); // Outputs : x : 1 - c : 1

1 Comment

This is my favourite
0

If you want to create a string literal including the single quotes instead of creating an actual char as described in other answers, do this:

Random rnd = new Random();
var x = rnd.Next(1,4).ToString(@"\'#\'");

Comments

0

You want to convert:

(int)1 to '1'
(int)2 to '2'
(int)3 to '3'
...

which is basically a function

char NumberToChar(int n) => (char)('0' + n);

Comments

0

One more option, because we don't have enough yet:

Random rnd = new Random();
var x = rnd.Next(1,4);
char c;
switch (x)
{
    case 1:
        c = '1';
        break;
    case 2:
        c = '2';
        break;
    case 3:
        c = '3';
        break;
}

1 Comment

Thank you. Now my answer is perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.