简体   繁体   中英

Alternative to switch — replacing characters

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?

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.. put("0", "zero"); put("1", "one"); //etc.. 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(' '); } 

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM