我正在尝试浏览字典并确定所述字典中的哪些单词遵循Java中的某个字母顺序。例如,模式i
,n
和g
将包含连枷 ing ,同时允许其他23个字母中的任何一个分隔i
,n
和g
,但仍必须采用相同的顺序(即名为isong
的单词仍符合条件,因为它遵循i
,{{1} }, THEN n
但不是“对齐”因为它跟随“i”,“g”,然后是“n”)。作为参考,“words.txt”是没有空格的字典文件。另外,我的教授不允许使用正则表达式。我要做的是修复findWords并读取文件,并将所有单词放入g
中名为“words”的String数组中。这是我的代码:
readDictionary
答案 0 :(得分:0)
你可以使用java正则表达式来帮助你做到这一点。 只需按照以下方式构建一个模式,即可搜索输入字符串是否依次包含“i”,“n”和“g”:
.*i.*n.*g.*
''正则表达式表示任何字符,'*'表示0到无穷大发生
以下代码快照供您参考使用java regex
public boolean matchPattern(String pattern, String inputString){
Pattern pattern =
Pattern.compile(pattern);
Matcher matcher =
pattern.matcher(inputString);
boolean found = false;
while (matcher.find()) {
return true;
}
return false;
}
使用此方法,只需调用它:
boolean foundIng = matchPattern(".*i.*n.*g.*" , "sample Input String ");
答案 1 :(得分:0)
import java.util.ArrayList;
static void findWords (String[] inputWords, char[] inputset)
{
ArrayList[] words = new ArrayList<String>(); // list of words that match the pattern. Lists* are of dynamic length, unlike their cousins, the array, which are fixed length. This one is typecasted to only be able to contain Strings
char[] ing = inputset; // the pattern
for (String s : inputWords)
{ // a for-each** loop through inputWords. Incidentally, in your original code, inputWords was called 'words', the same as your resulting list.
int wi = 0; // index in the 'ing' array that we are up to
for (char c : s.toCharArray())
{ // loop through every char in each word...
if (c == ing[wi])
{ // ... then check if the current character is the next one in the pattern...
wi++; // ... and if so, proceed to the next character in the pattern to match against
if (wi == ing.length)
{ // We've run out of characters to check against, so we know that the word matches the pattern
words.add(s); // add the word to the list of words that match the pattern
break; // break out of the checking loop, so that the first loop proceeds onto the next word in the dictionary
}
}
}
}
// Do something with your final list of words here
// String[] wordsList = words.toArray(new String[words.size()]); // Uncomment this line if you want the words list to be an array, instead of a list
}
* http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html是ArrayLists上的oracle javadoc页面 **有关for-each循环的详细信息,请参阅http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html