[英]How can I input exactly a five character string on a single line and then out put the string with spaces between each character? Java
I want a user to input five letters on a single line (for example the word "hello") and have the output be "hello". 我希望用户在一行上输入五个字母(例如单词“ hello”),输出为“ hello”。 I am able to do this with String.replace
(as seen below) but I need to use printf
and %s
to do it . 我可以使用String.replace
做到这一点(如下所示), 但是我需要使用printf
和%s
来做到这一点 。
Scanner scanner = new Scanner(System.in);
System.out.println("Enter five chatracters: ");
String charoutput = scanner.next();
String charoutput2 = charoutput.replace("", " ");
System.out.println("You have entered: " +charoutput2);
You can use printf
to print space for each character in string 您可以使用printf
为字符串中的每个字符打印空间
String str = "hello";
char[] ch =str.toCharArray();
for (char c:ch) {
System.out.printf("%2s", c); // h e l l o
}
or you can use Java 8 streams to do it in line 或者您可以使用Java 8流来实现
Arrays.stream(str.split("")).forEach(i->System.out.printf("%2s",i)); //h e l l o
There are multiple ways to solve this: 有多种解决方法:
Using String.join
: 使用String.join
:
String input = "Hello";
String result = String.join(" ", input.split(""));
// result now holds "H e l l o"
Using regex with replaceAll: 将regex与replaceAll一起使用:
String input = "Hello";
String result = input.replaceAll(".","$0 ").trim();
// result now holds "H e l l o"
Using a loop: 使用循环:
String input = "Hello";
int length = input.length;
for(int i=0; i<length; i++)
System.out.printf("%c%s", input.charAt(i), i<length ? " " : "");
// outputs "H e l l o"
Using printf
: 使用printf
:
String input = "Hello";
for(char c : input.toCharArray())
System.out.printf("%2c", c);
// outputs " H e l l o" (NOTE the leading space!)
My preference would be the String.join
, since it's basically a builtin of what you want to do. 我的首选是String.join
,因为它基本上是您要执行的内置操作。
Here is one of the ways you can do that: 这是您可以执行此操作的方法之一:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter five chatracters: ");
String charOutput = scanner.next();
String separatedChars = "";
for(char c: charOutput.toCharArray()) {
separatedChars += c + " ";
}
System.out.printf("You have entered: %s", separatedChars);
Here you iterate through each char of the received string and add it to the separatedChars
variable followed by a space. 在这里,您遍历接收到的字符串的每个字符,并将其添加到separatedChars
变量后跟一个空格。 Then, the result is printed using printf . 然后,使用printf打印结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.