Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a character array with characters from a string

Tags:

arrays

c#

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]);
like image 648
Naufal Nasiri Avatar asked Oct 05 '18 03:10

Naufal Nasiri


People also ask

How do you fill a character array?

fill(char[] a, char val) method assigns the specified char value to each element of the specified array of chars.

Can you make an array with characters?

Character Array in Java is an Array that holds character data types values. In Java programming, unlike C, a character array is different from a string array, and neither a string nor a character array can be terminated by the NUL character.

How do you populate a char array in Java?

Elements can be filled in a char array using the java. util. Arrays. fill() method.


1 Answers

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);
like image 111
go.. Avatar answered Sep 21 '22 22:09

go..