[英]Ignore special characters on StringTokenizer java
I want to ignore special characters like , " ; :
using string tokenizer. For example, if I enter: 我想使用字符串标记生成器忽略诸如
, " ; :
类的特殊字符。例如,如果输入:
He said, "That's not a good idea."
output should be: 输出应为:
He
Said
that
s
not
a
good
idea
This is my current code 这是我当前的代码
class Q_03
{
public static void main(String[] argv)
{
System.out.print("Enter text to break :- ");
Scanner sc = new Scanner(System.in);
String x = sc.nextLine();
StringTokenizer url = new StringTokenizer(x, " ");
while(url.hasMoreTokens())
{
System.out.println(url.nextToken());
}
}
}
You can replace that special characters with regex
like this: 您可以使用
regex
替换这些特殊字符,如下所示:
class Q_03 {
public static void main(String[] argv) {
System.out.print("Enter text to break :- ");
Scanner sc = new Scanner(System.in);
String x = sc.nextLine().replaceAll("[|;:,'\"]", " ");
StringTokenizer url = new StringTokenizer(x, " ");
while (url.hasMoreTokens()) {
System.out.println(url.nextToken());
}
}
}
You can add to this regexp "[;:,'\\"]"
whatever symbols you want, but some special symbols (like "
) must have been escaped with backslash \\"
. 您可以在此regexp
"[;:,'\\"]"
任何所需的符号,但是某些特殊符号(如"
)必须已使用反斜杠\\"
进行转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.