开发者

Add character a place in String

I'm trying to make a method that shall help me to spell world right. After addChar have return its work based on the input "famili", I want the result array to contain the word "familiy". Now the method removes a character from the string and replace it with the current char in alpha[], can someone please give me some help to make this method to add the char from alpha[] between two characters and not delete one to get space.

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开发者_如何学Go(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;
        }
}


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

Working link


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);


Try to use LinkedList.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜