0

我正在尝试制定一种方法来帮助我正确拼写世界。在addChar根据输入返回其工作后"famili",我希望结果数组包含单词"familiy"。现在该方法从字符串中删除一个字符并将其替换为 in 中的当前字符alpha[],有人可以给我一些帮助以使此方法从alpha[]两个字符之间添加字符而不是删除一个字符以获得空间。

class Main {
       char [] alpha = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                        'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'y', 'z'};
        public static void main(String [] args) {

            Main m = new Main();
            String [] result = m.addChar("famil");
        }

        public String[] addChar(String word) {

            String [] words = new String[word.length() * alpha.length];
            int k = 0;

            for(int i = 0; i < alpha.length; i++) {
                for(int j = 0; j < word.length(); j++) {
                    StringBuffer buf = new StringBuffer(word);
                    buf.setCharAt(j, alpha[i]);
                    words[k++] = buf.toString();
                }
            }
            return words;
        }
}
4

3 回答 3

3

You can make use of the insert method of the StringBuffer class in place of setCharAt.

Working link

于 2010-10-24T19:57:05.800 回答
1

I would probably solve it like this.

for (int i = 0; i < alpha.length; i++)
    for (int j = 0; j < word.length(); j++)
        words[k++] = word.substring(0, j) + alpha[i] + word.substring(j);
于 2010-10-24T19:58:51.683 回答
0

Try to use LinkedList.

于 2010-10-24T19:55:56.057 回答