如何在java中读取字符串中的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26306135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read characters in a string in java
提问by Ahaha
I'm new in java, so sorry if this is an obvious question.
我是 Java 新手,如果这是一个明显的问题,我很抱歉。
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
我正在尝试逐字符读取字符串以创建树节点。例如,输入"HJIOADH"
和节点是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 != '/') {
Scanner reader = new Scanner(System.in); System.out.println("输入你的节点为大写字母,没有空格,末尾有'/'"); int i = 0; 字符节点 = reader.next().charAt(i); 而(节点!= '/'){
CreateNode(node); // this is a function to create a tree node
i++;
node = reader.next().charAt(i);
}
采纳答案by corsiKa
You only want to next()
your reader once, unless it has a lot of the same toke nrepeated again and again.
你只想要next()
你的读者一次,除非它一次又一次地重复了很多相同的标记。
String nodes = reader.next();
for(int i = 0; i < nodes.length(); i++) {
System.out.println(nodes.charAt(i));
}
回答by Em Ae
as Braj mentioned you can try reader.toCharArray()
and to then you can easily use the loop
正如 Braj 提到的,你可以尝试reader.toCharArray()
,然后你可以轻松地使用循环
char[] array = reader.toCharArray();
for (char ch : array) {
System.out.println (ch);
}