in C#: looping through a string or a string array if the index is higher than the length of the string

85 Views Asked by At

So I'm very new to C# and trying to learn some basics so I apologize if I have any of the terminology wrong, please feel free to let me know if I can clarify anything.

I'm trying to fetch an object of the index position, decided by another int variable, in a string array. The variable must be able to be larger than the number of objects in the string array, so far I get "IndexOutOfRangeException, which is to be expected. I would like it to keep looking and just start over in the array, much like a loop would work.

So these are the relevant strings for what I've tried:

string alf = ("abcdefghijklmnopqrstuvwxyz");

string[] alflist = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};

What I've tried is this: string output = alflist[Encryption.key];

Where Encryption.key is called form another class, and this is the int that could be (and in this instance is) larger than the 26 positions of alflist.

If Encryption.key = 30 I would like output to be = "e" (since a=0 & 26).

I have also tried to use alf.substring(Encryption.key, 1) but I get the same error.

Thanks for any guidance on this

1

There are 1 best solutions below

5
Joel Coehoorn On

You can use the modulus (%) operator. Also, strings can already provide characters by index using the same bracket notation as arrays; there's no need to create a separate array:

string alf = "abcdefghijklmnopqrstuvwxyz";
int index = Encryption.Key % alf.Length;
char result = alf[index];

Or if you need a string instead of a character:

string alf = "abcdefghijklmnopqrstuvwxyz";
int index = Encryption.Key % alf.Length;
string result = alf[index].ToString();

But if you did want an array, you can could get it like this:

string alf = "abcdefghijklmnopqrstuvwxyz";
var alfArray = alf.ToCharArray(); // List is not an array. It means something different in C#