Java character initializer

I tried to create a program that separates characters. The question arises:

"Create a char array and use an array initializer to initialize the array with the characters in the Hello there line. Display the contents of the array using a for statement. Separate each character in the array using a space."


The program I made:

String ini="Hi there";
  char[] array=new  char[ini.length()];


  for(int count=0;count<array.length;count++){

  System.out.print(" "+array[count]);


  }

      

What should I do to fix this problem?

+3


source to share


5 answers


Here's how you can convert a String array to a char array:

String str = "someString"; 
char[] charArray = str.toCharArray();

      



I would recommend that you use an IDE while programming to easily see what methods the class contains (in which case you should be able to find toCharArray()

) and compile errors like the ones you have above. You should also check out the documentation, which in this case would be this String documentation .

Also, always mention what kind of compilation errors you get. It was easy to notice in this case, but when it isn't, you won't be able to get answers unless you include it in your message.

+12


source


you are doing it wrong, you first split the string using space as separator using String.split () and filled the char array with characters.

or even easier to just use String.charAt()

in a loop to fill the array like below:

String ini="Hi there";
  char[] array=new  char[ini.length()];

  for(int count=0;count<array.length;count++){
         array[count] = ini.charAt(count);
  System.out.print(" "+array[count]);
  }

      



or one liner will be

  String ini="Hi there";
  char[] array=ini.toCharArray();

      

0


source


Here is the code

String str = "Hi There";
char[] arr = str.toCharArray();

for(int i=0;i<arr.length;i++)
    System.out.print(" "+arr[i]);

      

0


source


Instead of the above u method, you can achieve a solution simply by the following method.

public static void main(String args[]) {
    String ini = "Hi there";
    for (int i = 0; i < ini.length(); i++) {
        System.out.print(" " + ini.charAt(i));
    }
}

      

0


source


char array[] = new String("Hi there").toCharArray();
for(char c : array)
    System.out.print(c + " ");

      

0


source







All Articles