I want to insert every character into each index of a string in order to check if it is a word in the dictionary. For example, Word -> complte I want my code to insert (a-z)complte c(a-z)omplte co(a-z)mplte And then check if It is in the dictionary. Currently my code only adds each character at the front of the string for some reason.
Scanner myDocReader = new Scanner(myDoc);
while(myDocReader.hasNext()) {;;
String word = myDocReader.next();
word = word.toLowerCase();
word = word.replaceAll("\\p{Punct}","");//Removes all punctuation
//Case 1: Add One Character in Each Possible Position
StringBuilder newWord = new StringBuilder(word);
StringBuilder reset = new StringBuilder(word);
if(!correctWords.contains(word)) {
//Add One Character in each possible Position
for(int i=0; i<word.length(); i ) {
for(char ch = 'a'; ch <= 'z'; ch ) {
newWord = newWord.insert(i, ch);
String newWord1 = newWord.toString();
System.out.println(newWord1);
if(correctWords.contains(newWord1)) {
System.out.println("Suggestion: " word "->" newWord1);
newWord = reset;
continue;
}
newWord = reset;
continue;
}
}
Example output of current Code a(string) b(string) cb(string) dcb(string) What I want: a(string) b(string) c(string) d(string) .....
CodePudding user response:
public static void main(String[] args) {
String word = "complte";
Set<String> dictionary = new HashSet<>();
dictionary.add("complete");
List<String> suggestions = new ArrayList<>();
for (int i = 1; i < word.length(); i ) {
for (byte j = 'a'; j <= 'z'; j ) {
StringBuilder builder = new StringBuilder();
builder.append(word.substring(0, i));
builder.append((char) j);
builder.append(word.substring(i, word.length()));
if (dictionary.contains(builder.toString())) {
suggestions.add(builder.toString());
}
}
}
if (!suggestions.isEmpty()) {
System.out.println("Suggestions: ");
for (String suggestion : suggestions) {
System.out.println(suggestion);
}
}
}
CodePudding user response:
If you write newWord = reset
then newWord
and reset
will refer to the same object and thus modifying newWord
will modify reset
also. This is my implementation :
if(!correctWords.contains(word)) {
//Add One Character in each possible Position
for(int i=0; i<word.length(); i ) {
for(char ch = 'a'; ch <= 'z'; ch ) {
newWord = newWord.insert(i, ch);
String newWord1 = newWord.toString();
System.out.println(newWord1);
if(correctWords.contains(newWord1)) {
System.out.println("Suggestion: " word "->" newWord1);
newWord.replace(i,i 1,"");
// newWord = reset;
continue;
}
newWord.replace(i,i 1,"");
// newWord = reset;
continue;
}
}
}