删除Java中字符串的所有非字母字符
给定一个字符串str,由非字母字符组成。任务是删除 str 的所有非字母字符并在新行上打印单词。
例子:
Input: str = “Hello, how are you ?”
Output:
Hello
how
are
you
comma(, ), white space and question mark (?) are removed and there are total 4 words in string s.
Each token is printed in the same order in which it appears in string s.
Input: “Azad is a good boy, isn’ t he ?”
Output:
Azad
is
a
good
boy
isn
t
he
方法:非字母字符基本上是任何不是数字或字母的字符。它可以是英文字母、空格、感叹号 (!)、逗号 (, )、问号 (?)、句点 (.)、下划线 (_)、撇号 (') 和 at 符号 (@)。方法是使用Java String.split 方法将String, s 拆分成一个子字符串数组。然后以与在 String 中出现的顺序相同的顺序在新行上打印每个 n 单词。
下面是上述方法的实现:
// Java program to split all
// non-alphabetical characters
import java.util.Scanner;
public class Main {
// Function to trim the non-alphabetical characters
static void printwords(String str)
{
// eliminate leading and trailing spaces
str = str.trim();
// split all non-alphabetic characters
String delims = "\\W+"; // split any non word
String[] tokens = str.split(delims);
// print the tokens
for (String item : tokens) {
System.out.println(item + " ");
}
}
public static void main(String[] args)
{
String str = "Hello, how are you ?";
printwords(str);
}
}
输出:
Hello
how
are
you
时间复杂度: O(N)