Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read characters in a string in java

Tags:

java

string

I'm new in java, so sorry if this is an obvious question.

I'm trying to read a string character by character to create tree nodes. for example, input "HJIOADH" And the nodes are H J I O A D H

I noticed that

char node = reader.next().charAt(0);  I can get the first char H by this
char node = reader.next().charAt(1);  I can get the second char J by this

Can I use a cycle to get all the characters? like

for i to n
    node = reader.next().charAt(i)

I tried but it doesn't work.

How I am suppose to do that?

Thanks a lot for any help.

Scanner reader = new Scanner(System.in); System.out.println("input your nodes as capital letters without space and '/' at the end"); int i = 0; char node = reader.next().charAt(i); while (node != '/') {

        CreateNode(node); // this is a function to create a tree node
        i++;
        node = reader.next().charAt(i);

    }
like image 571
Ahaha Avatar asked Oct 10 '14 18:10

Ahaha


People also ask

Can you access characters in a string Java?

To access character of a string in Java, use the charAt() method. The position is to be added as the parameter. String str = "laptop"; Let's find the character at the 4th position using charAt() method.

How do I extract a character in Java?

charAt(int index) To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. Example 1: Returns the char value at the specified index of this string. The first char value is at index 0.


2 Answers

You only want to next() your reader once, unless it has a lot of the same toke nrepeated again and again.

String nodes = reader.next();
for(int i = 0; i < nodes.length(); i++) {
    System.out.println(nodes.charAt(i));
}
like image 90
corsiKa Avatar answered Oct 14 '22 11:10

corsiKa


as Braj mentioned you can try reader.toCharArray() and to then you can easily use the loop

char[] array = reader.toCharArray();
for (char ch : array) {
    System.out.println (ch);
}
like image 23
Em Ae Avatar answered Oct 14 '22 13:10

Em Ae