0

I should from string txt "jvn" , get only 1 random character, but for some reason it wont work i also tried after the loop to Convert my char again to String but it doesn't work, I don't have return value

static char Zufallszeichen(string s)
{

    Random rnd = new Random();
    string x = "jvn";

    string result = "";
    Convert.ToChar(x);

    for (int i = 0; i < 1; i++)
    {
        result += x.Substring(rnd.Next(0, x.Length), 1);

    }

    return x;
}
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
Kevin Garnick
  • 94
  • 1
  • 9

2 Answers2

1

I assume that you want to get a random character from an input-string, right?

First things first: You seem fairly new to C# or programming in general. Maybe you want some tutorials. Or you could just grab a good programming book.

Nonetheless, Lets go through this:

static char Zufallszeichen(string s) /* You never use the argument, why do you have one* */
    {

        Random rnd = new Random();
        string x = "jvn"; // You are creating this string and returning it unchanged at the end

        string result = "";
        Convert.ToChar(x); // This ->returns<- the input as char... so basicly you have to catch the value. But why would you that in the first place

        for (int i = 0; i < 1; i++) // You're looping for 1 iteration (i.e. running the code inside once)
        {
            result += x.Substring(rnd.Next(0, x.Length), 1); // You're appending a random character to the result _string_ but never returning it.

        }

        return x; // You will only return jvn, as x has remained unchanged.
    }

Here a very simple approch:

public static char GetRandomCharacterFromString(string input)
{
    // Do some basic null-checking
    if(input == null)
    {
        return char.MinValue; // Or throw an exception or, or, or...
    }

    var random = new Random();
    var inputAsCharArray = input.ToCharArray();
    var index = random.Next(0, input.Length);

    return inputAsCharArray[index];
}

EDIT: I know that there are a more easier or simpler answers, but I hope that this approach is more "understandable".

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Link
  • 1,307
  • 1
  • 11
  • 23
0

Followig code working for me:

static char randomLetter(string s)
    {

        Random rnd = new Random();
        int index = rnd.Next (0, s.Length);
        return s[index];
    }
char leter = randomLetter ("abcdef");
mozkomor05
  • 1,367
  • 11
  • 21