❔ Lists
How do I make a list? And how do I make it so it picks one of the words/numbers in the strings? (e.g. like random.randint([1, 2, 3]) or random.choice([Rock, Paper, Scissors]) in Python)
16 Replies
You can use
Random.Shared.Next(0, list.Count)
to get a random index from the list, then you can use that to get a random element.
Well, you first need to get a random indexI meant to ping the message, sorry for deleting it.
You can then index the list using that index
So indexes for strings are the same for numbers?
Wdym?
Indexes are almost always integers
Things like lists, arrays, and strings can be indexed by using
[]
I meant, are string indexes the same as integer indexes?
Like:
string myString = "Hello"
Console.WriteLine(myString[0])
I don't know what "integer index" is supposed to mean
Integers are used to index things
Never mind, but to get a random index, would it be like
string myString = "Hello"
Console.WriteLine(myString.IndexOf.random)
I'm not sure if that's valid code
Well, the quintessential method to get a random number is
Random.Shared.Next
If you want to get a random index from a string, then you firstly need the length of the string, which you can get using myString.Length
.
Secondly you need to call Random.Shared.Next
, which takes two arguments, the first being the lower bound (which in this case will be 0) and the second being the exclusive upper bound (which in this case is the length of the string).How would that be implemented into code? (Sorry for all this hassle)
I trust that you'll be able to analyze this and not just blindly copy it
Of course. One last question, does var stand for variable? I don't want to assume it does
it does
var x = 0;
means "create a variable called 'x' has has the type of whatever is on the other side of the = sign"
You can also write int x = 0;
to specify the type explicitly, it's just up to preference.Thanks for all the help; appreciated.
if you index string its like c# would call
ToCharArray()
on that string in the background. an array of any type can be accessed the same wayWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.