[英]How do I take an input and make the program print out each letter on a new line while making every space encounter to print out “<space>”?
import java.util.Scanner;
public class TwoDotSevenNumbaTwo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input;
int num1, num2, leng;
char word;
Scanner inputscan = new Scanner(System.in);
System.out.println("Give me some love baby");
input = inputscan.nextLine();
leng = input.length();
num1 = 0;
num2 = 1;
while (num1 < leng) {
input = input.replaceAll(" ", "<space>");
System.out.println(input.charAt(num1));
num1++;
}
}
}
I can't seem to figure out how to get the <space>
on a single line. 我似乎无法弄清楚如何在单行上获取
<space>
。 I know I can't do it because it is a char but I can't find a way around it. 我知道我做不到,因为它是一个字符,但是我找不到解决方法。
You could do 你可以做
for(int i = 0; i < leng; ++i) {
char x = input.charAt(i);
System.out.println(x == ' ' ? "<space>" : x);
}
Once you've stored the input as a String, you can write: 将输入存储为字符串后,可以编写:
// Break the string into individual chars
for (char c: input.toCharArray()) {
if (c == ' ') { // If the char is a space...
System.out.println("<space>");
}
else { // Otherwise...
System.out.println(c);
}
}
Regex powa: 正则表达式powa:
yourText.replaceAll(".", "$0\n").replaceAll(" ","<space>");
Explanation: 说明:
First replaceAll takes every charachter ( .
= any character) and replaces it with the same character ( $0
= matched text) followed by a newline \\n
, thusly every character is on separate line. 首先replaceAll接受每个字符(
.
=任何字符),并用相同的字符( $0
=匹配的文本)替换,后跟换行符\\n
,因此每个字符都位于单独的行上。
Second replaceAll just replaces every acctual space with the word "<space>"
第二个replaceAll只是用单词
"<space>"
替换每个实际的空格
For java regex tutorial, you can follow this link or use your favourite search engine to find plenty more. 对于Java regex教程,您可以单击此链接或使用自己喜欢的搜索引擎查找更多内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.