Alternative to switch — replacing characters

醉酒当歌 提交于 2019-12-12 04:55:07

问题


I was required to write a program for class which:

  1. Accepted a .txt file
  2. Convert numbers 0-9 in the file to their text equivalent (if the number is at beginning of sentence, use uppercase)
  3. Print the finished sentences to a new file

Example:

The 8 eggs were separated into 3 groups.

Would be converted to:

The eight eggs were separated into three groups.

Currently I am using a (very) long switch statement with a StringBuilder to complete the task:

switch(sb.charAt(i)){
        case '0':
            if (i == 0)
                sb.replace(i, i+1, "Zero");
            else
                sb.replace(i, i+1, "zero");
            break;
        case '1':
            if (i == 0)
                sb.replace(i, i+1, "One");
            else
                sb.replace(i, i+1, "one");
            break;
        ..... 
}

There is a more advanced/efficient way to accomplish this task?


回答1:


Probably you're looking for HashMap. This can help:

  1. Create static HashMap<String, String> DIGITS and use put("0", "zero"); put("1", "one"); //etc.. to initialize it.
  2. Split your input string using string.split(" "); this will create an array of strings like this: {"The","8","eggs",...}.
  3. Use StringBuilder to build an answer:

    for (String s : splitted) {
        if (DIGITS.contains(s))
            sb.append(DIGITS.get(s));
        else
            sb.append(s);
        sb.append(' ');
    }
    



回答2:


You can do it this way.

Sting[] token = statement.split(" ");
String newStatement = "";
for(int x=0; x<token.length; x++){
    if(token[x].matches("[0-9]+"))
        newStatement  += convertToText(token[x]) + " ";
    else
        newStatement  += token[x] + " ";        
}

public static String converetToText(String str){
    String[] text = {"zero", "one", "two", "three", "four", "five", "six", "seven". "eight", "nine"};
    return text[Integer.parseInt(str)];
}

Your entire program is completed.


Explanation:

  1. Split the given statement by spaces.
  2. Store individual word into a string array (token[])
  3. Check each individual word whether it is a number
  4. If it is a number convert to text and add it to new statement.
  5. If it is a text add it straight into your new statement.



回答3:


I would do something like this. Iterate through the characters using Character.isDigit to check if they should be replaced. If so simply look up the replacement string in an array using (character - '0') as the index:

    String[] textArray =  new String[]{ "zero", "one", "two",
                                        "three", "four", "five",
                                        "six", "seven", "eight", "nine" };

    StringBuilder sb = new StringBuilder("abc 1 xyz 8");
    System.out.println(sb);

    for (int i=0; i<sb.length(); ++i) {
        char c = sb.charAt(i);
        if (Character.isDigit(c)) {
            sb.replace(i, i+1, textArray[c - '0']);
        }
    }
    System.out.println(sb);

Output is:

abc 1 xyz 8
abc one xyz eight


来源:https://stackoverflow.com/questions/28799408/alternative-to-switch-replacing-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!