我如何找到特定长度的单词,忽略标点符号

  • 本文关键字:单词 标点符号 何找 java
  • 更新时间 :
  • 英文 :


我有一个程序,它将数组读入列表,计算所有单词,查找特定单词,并查找特定长度的单词。特别是在bigLongWords方法中,我如何查找长度为x或更多的单词,但忽略标点符号?例如,如果我有字符串&;the Rolling Stones!&;和bigLongWords(7),我想让它只找到"滚动",但它也包括"石头"!。

public class JavaCharacterisLetterExample1 {  
public static void main(String[] args) {  
// Create three char primitives ch1, ch2 and ch3.  
char ch1, ch2, ch3;  
// Assign the values to ch1, ch2 and ch3.  
ch1 = 'A';  
ch2 = '9';  
ch3 = 'e';  
// Create three boolean primitives b1, b2 and b3;  
boolean b1, b2, b3;  
// Check whether ch1, ch2 and ch3 are letters or not and assign the results to b1, b2 and b3.  
b1 = Character.isLetter(ch1);  
b2 = Character.isLetter(ch2);  
b3 = Character.isLetter(ch3);  
String str1 = "The character "+ch1 + " is a letter: " + b1;  
String str2 = "The character "+ch2 + " is a letter: " + b2;  
String str3 = "The character "+ch3 + " is a letter: " + b3;  
// Print the values of b1, b2 and b3.  
System.out.println( str1 );  
System.out.println( str2 );  
System.out.println( str3 );  

}

Java有一个内置方法"isLetter"如果字符不是字母,结果是false。下面的代码返回"false">

String s = "test!";
System.out.println(Character.isLetter(s.charAt(4)));

将bigLongWords方法替换为:

public int bigLongWords(int len){ //ignore punctuation
int count = 0;
for (int i = 0;i<list.size();i++){
boolean isWord = true;
for (int j = 0;j<list.get(i).length();j++){  
if(!Character.isLetter(list.get(i).charAt(j))) {
isWord = false;
}
}
if(list.get(i).length() >= len && isWord == true){
// you can test isWord before this if clause 
// and break if it is false but this works too
list.set(i,  list.get(i).toUpperCase());
count++;
}
}
return count;
}

有两种方法:

  1. 从数组中读取时,去掉单词中的标点符号。
  2. 当响应像"查找长度大于等于7的所有单词"这样的查询时,您可以从单词中删除标点符号并返回过滤后的列表。

选项1的优点是工作在读取时间之前完成,并且读取速度非常快。选项1的缺点是,你要对所有单词都这么做。如果从来没有查询长度为3或以上的单词,您仍然需要预处理这些单词的时间。

选项2的优点是动态过滤,因此只有在查询该单词长度时才需要付费。选项2的缺点正是选项2的优点。如果你得到同样的查询10次,你做同样的工作10次。

您可以使用混合方法,动态过滤,但随后异步更新源数据,因此下次您不会再进行相同的过滤。

相关内容

最新更新