忽略 StringTokenizer 上的特殊字符
Ignore special characters on StringTokenizer
我想使用字符串分词器忽略 ,
"
;
:
等特殊字符。
例如,如果我输入:
He said, "That's not a good idea."
输出应该是:
He
Said
that
s
not
a
good
idea
这是我当前的代码
class MyClass
{
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());
}
}
}
您可以像这样用 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());
}
}
}
您可以在此正则表达式 "[;:,'\"]"
中添加您想要的任何符号,但某些特殊符号(如 "
)必须使用反斜杠进行转义 \"
.
我想使用字符串分词器忽略 ,
"
;
:
等特殊字符。
例如,如果我输入:
He said, "That's not a good idea."
输出应该是:
He
Said
that
s
not
a
good
idea
这是我当前的代码
class MyClass
{
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());
}
}
}
您可以像这样用 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());
}
}
}
您可以在此正则表达式 "[;:,'\"]"
中添加您想要的任何符号,但某些特殊符号(如 "
)必须使用反斜杠进行转义 \"
.