【问题标题】:Using nested for loops to replace characters in an array of strings with the corresponding characters to the left or the right on a keyboard使用嵌套的 for 循环将字符串数组中的字符替换为键盘左侧或右侧的相应字符
【发布时间】:2016-04-20 02:34:53
【问题描述】:

我正在创建一个程序,该程序将使用 200,000 多个单词的读入文件向用户输入的文本消息提供建议(如拼写检查)。

我需要创建一个读取单词数组的方法(已根据消息的长度排序到位置 0-n),然后将位置 n 处的每个字符替换为左侧的相应字符或键盘上的右侧并将它们存储到 ArrayList 中。然后,这将被传递给一个方法,该方法将读取 ArrayList,将其与读入的字典交叉引用,并返回一个 ArrayList,其中的组合实际上是单词。

EX:你好(位置 0)那里(位置 1) 替代词:Hello、Jello、Gello、Hrllo、Hwllo 等

我一直在努力寻找一种方法来将位置 n 处的字符替换为键盘左侧或右侧的字符。有什么建议吗?

这是目前为止的代码:

public ArrayList <String> alternateWords (String [] w)
    {

        //declarations

        int p = 0; //position of characters inside array
        ArrayList<String> potentialWords = new ArrayList<String>(); //ArrayList to hold all potential words

        //Traverse array and replace letters in each word, then store in ArrayList

        for (int i = 0; i < w.length; i++) //loop for each word in a text message
        {
            for (int j = 0; j < w[p].length(); i++) //loop for each character in a text message
            {

                //REPLACE HAPPENS HERE
                p++; //increment position of character check
                //Store in arrayList

            } //End inner For

        } //End outer For

    } //End alternateWords

【问题讨论】:

    标签: java arrays string arraylist replace


    【解决方案1】:

    由于这类数据是静态的(对于给定类型的键盘),最好用enum 表示。

    这是一个部分示例:

    public class Scratch {
        public static void main(String[] args) throws Exception {
            char key = 'a';
            System.out.println(NextTo.valueOf(key).getLeft()+" is left of "+key);
            System.out.println(NextTo.valueOf(key).getRight()+" is right of "+key);
        }
    }
    
    enum NextTo {
        a(null, 's'),
        s('a', 'd'),
        d('s', 'f'),
        f('d', 'g');
        // ...
    
        private Character left;
        private Character right;
    
        public Character getLeft() {
            return left;
        }
        public Character getRight() {
            return right;
        }
        public static NextTo valueOf(char c) {
            return NextTo.valueOf(String.valueOf(c));
        }
    
        private NextTo(Character left, Character right) {
            this.left = left;
            this.right = right;
        }
    }
    

    哪个输出

    null 在 a
    的左边 s 是 a 的右边


    我没有添加任何类型的错误检查或对大写字母的支持,但你明白了。

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多