问题概要:
给定一个字符串“s”,与正则表达式 [A-Za-z !,?._'@]+ 匹配,我必须将该字符串拆分为标记。 “我们将 token 定义为一个或多个连续的英文字母。”然后,打印 token 数,然后在新行上打印每个 token 。
示例输入:
He is a very very good boy, isn't he?
示例输出:
10
He
is
a
very
very
good
boy
isn
t
he
说明:
字符串“s”中总共有 10 个这样的标记,每个标记的打印顺序与其在字符串“s”中出现的顺序相同。
我的方法
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
String[] tokens = s.split("[ !,?._'@]+");
int tokenCount = 0;
for (String token : tokens) {
if (!token.isEmpty()) {
tokenCount++;
System.out.println(token);
}
}
System.out.println(tokenCount);
}
}
我的输出:
He
is
a
very
very
good
boy
isn
t
he
10
我遇到的唯一问题是数字打印在最后一行,而我一开始就需要它。我尝试过使用 print 语句,并将其放在我认为它可以像 for 循环上方和更多地方一样工作的地方,但它只会产生错误或打印错误的值。
我只需要一些关于如何将数字打印在顶部的快速建议。谢谢。
最佳答案
喜欢@markspace说:
You can count the number of tokens without using a loop or the ++ operator. It's just the length of the array.
所以,你甚至不需要 tokenCount
,tokenCount
是数组大小:
System.out.println(tokens.length);
for (String token : tokens) {
if (!token.isEmpty()) {
System.out.println(token);
}
}
但是,就像 @Computable说:
...if the line started with a delimiter the array length solution would produce an incorrect count hence the isEmpty check...
所以,如果 s
可以从匹配器字符开始,我看到两种解决方案:
首先是验证 s
的第一个字符(并在必要时将其删除)在 split
之前:
String regex = "[ !,?._'@]+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String firstMatch = matcher.group();
if (s.startsWith(firstMatch)) {
s = s.substring(firstMatch.length());
}
}
String[] tokens = s.split(regex);
第二个是使用 List<String>
基于您的代码:
List<String> resultTokens = new ArrayList<String>();
for (String token : tokens) {
if (!token.isEmpty()) {
resultTokens.add(token);
}
}
System.out.println(resultTokens.size());
resultTokens.forEach(System.out::println);
注意:使用List<String>
您不需要使用tokenCount
,您只需调用 size()
即可.
关于java - 语句打印在错误的行(Java Token 问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77113098/