java 如何一次打印一个字符的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33137295/
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 print a string one character at a time?
提问by Todd
I am having trouble printing a string one character at a time in java. I have to input a string and output it one letter per line. My code is as follows
我在 java 中一次打印一个字符时遇到问题。我必须输入一个字符串并每行输出一个字母。我的代码如下
import java.util.*;
public class StringToMultiLines
{
public static void main(String[] args)
{
String myString;
int placeInString = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string.");
myString = scan.nextLine();
while(placeInString <= myString.length())
{
System.out.println("" + myString.substring(placeInString));
placeInString ++;
}
}
}
This ouptuts the following' Please enter a string. Hello Hello ello llo lo o
这会输出以下内容'请输入一个字符串。你好 你好 hello lo lo o
I have also tried this with no luck
我也试过这个,但没有运气
System.out.println("" + myString.subsstring(0, placeInString));
and
和
System.out.println("" + myString.subsstring(placeInString, placeInString));
回答by MadProgrammer
You could simply use a for-loop
and String#charAt
(or String#toCharArray
)
你可以简单地使用一个for-loop
和String#charAt
(或String#toCharArray
)
for (int index = 0; index < myString.length(); index++) {
System.out.println(myString.charAt(index));
}
or
或者
for (char c : myString.toCharArray()) {
System.out.println(c);
}
Have a look at The for
statementand the String
JavaDocsfor more details
看一看的for
语句和String
的JavaDoc了解详情
回答by emlai
You're looking for charAt
:
您正在寻找charAt
:
System.out.println(myString.charAt(placeInString));
And remember that indices start from 0, so myString.length()
is an invalid index. Thus you need
请记住,索引从 0 开始,因此myString.length()
是无效索引。因此你需要
while (placeInString < myString.length())
instead of
代替
while (placeInString <= myString.length())