Filling a character array with characters from a string

  • A+
Category:Languages

I'm trying to fill an array with characters from a string inputted via console. I've tried the code bellow but it doesnt seem to work. I get Index out Of Range exception in the for loop part, and i didn't understand why it occured. Is the for loop range incorrect? Any insight would be greatly appreciated

            Console.WriteLine("Enter a string: ");             var name = Console.ReadLine();              var intoarray = new char[name.Length];             for (var i = 0; i <= intoarray.Length; i++)             {                 intoarray[i] = name[i];             }             foreach (var n in intoarray)                 Console.WriteLine(intoarray[n]); 

 


using ToCharArray() strings can be converted into character arrays.

Console.WriteLine("Enter a string: "); var name = Console.ReadLine();  var intoarray= name.ToCharArray();  foreach (var n in intoarray)     Console.WriteLine(n); 

if you are using foreach, you should wait for the index to behave as if you were taking the value.

Console.WriteLine(n); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: