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++;
}
}
}
我似乎不知道如何在单行上得到<space>
。我知道我不能这样做,因为它是一个字符,但我找不到解决它的方法
你可以做
for(int i = 0; i < leng; ++i) {
char x = input.charAt(i);
System.out.println(x == ' ' ? "<space>" : x);
}
一旦您将输入存储为String,您可以这样写:
// 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);
}
}
正则表达式:
yourText.replaceAll(".", "$0n").replaceAll(" ","<space>");
解释:
首先replaceAll将每个字符(.
=任何字符)替换为相同的字符($0
=匹配的文本),后跟换行符n
,因此每个字符都在单独的行上。
Second replaceAll只是用单词"<space>"
替换每个实际的空格
关于java正则表达式教程,您可以点击此链接或使用您最喜欢的搜索引擎查找更多内容。