将数字从字符串转换为单词

时间:2013-04-26 02:16:39

标签: java string loops char

我的cs类的这个作业的目标是在字符串中搜索数字并将其更改为书面形式

ex:4 -> four

这是一项相对简单的任务。但是我有两个问题:

1)由于我当前的代码,如果我转换了一串“8”并尝试将其设为“8”,它将无效,因为它是比字符串的当前长度长。

2)通过字符串连续处理多个数字char。我有点想通了。如果您使用某些Strings运行我所拥有的功能。我们应该用连字符分隔多个数字字符。

这是我的代码:

public class NumberConversion {

    /**
     * * Class Constants **
     */
    /**
     * * Class Variables **
     */

    /* No class variables are needed due to the applet not having a state.
     All it does is simply convert. */
    /**
     * * Class Arrays **
     */
    char numberChar[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    String numbers[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

    /**
     * * Accessor Methods **
     */
    /**
     * * Transformer/Mutator Methods **
     */
    public void writeNumber(String phrase) {
        /**
         * Local Variables *
         */
        String newPhrase = "";
        int j = 0;
        int k = 0;

        phrase = phrase.trim();

        /**
         * * Counts through the length of phrase **
         */
        for (int i = 0; i < phrase.length(); i++) {
            /**
             * * If the current char is a number char, enter the next repitition
             * structure **
             */
            int l = i + 1;

            if (isNumber(phrase.charAt(i)) && isNumber(phrase.charAt(i + 1))) {
                boolean searchArray = true;

                do {
                    if (numberChar[ j] == phrase.charAt(i)) {
                        searchArray = false;
                    }

                    j++;

                } while (searchArray && j < numberChar.length);

                phrase = phrase.replace(Character.toString(phrase.charAt(i)), numbers[ j - 1] + "-"); //error HERE

            }

            if (isNumber(phrase.charAt(i))) {
                boolean searchArray = true;

                do {
                    /**
                     * * Counts through numberChar array to see which char was
                     * found in the phrase. Stops when found **
                     */
                    if (numberChar[ k] == phrase.charAt(i)) {
                        searchArray = false;
                    }

                    k++;

                } while (searchArray && k <= numberChar.length);

                /**
                 * * Changes char to string and replaces it with the matching
                 * String numbers array element **
                 */
                phrase = phrase.replace(Character.toString(phrase.charAt(i)), numbers[ k - 1]);
            }
            phrase = phrase.replace("- ", " ");
        }
        System.out.println(phrase); // Prints the changed phrase.
    }

    /**
     * * Helper Methods **
     */
    /**
     * * Observer Methods **
     */
    public boolean isNumber(char input) {
        boolean isNumber = false; // Initially fails

        for (int i = 0; i < numberChar.length; i++) {
            /**
             * * If input matches a number char, method returns true **
             */
            if (input == numberChar[ i]) {
                isNumber = true;
            }
        }
        return isNumber;
    }
}

3 个答案:

答案 0 :(得分:0)

不要替换当前字符串中的数字,创建新字符串,并继续追加它。然后,您可以避免许多不必要的验证。

    List<Char> myNumberChar = Arrays.asList(numberChar);
    List<Char> myNumbers = Arrays.asList(numbers);
    StringBuilder mySB = new StringBuilder();
    //String myResultString = ""; // If you don't want to use StringBuilder
    for (int i = 0; i < phrase.length(); i++) {
        mySB.append(myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-");
        //myResultString = myResultString + myNumbers.get(myNumberChar.getIndexOf(phrase.charAt(i)))+"-"; //Again, for no StringBuilder case
    }
    String myResult = mySB.toString();
    // No need to do the above in no StringBuilder case, just use myResultString in place of myResult
    System.out.println(myResult.subString(0, myResult.length - 1)); // removed the last hyphen

答案 1 :(得分:0)

我会使用String.replace

for(int i = 0; i < 10; i++) {
   str = str.replace(numberChar[i] + "", numbers[i]);
}

答案 2 :(得分:0)

    public class NumberConversion

{

/*** Class Variables ***/

/* No class variables are needed due to the applet not having a state.
   All it does is simply convert. */

/*** Class Arrays ***/

char numberChar [] = {'0','1','2','3','4',                          '5','6','7','8','9'};

String numberWord [] = {“zero”,“one”,“two”,“three”,“four”,                         “五”,“六”,“七”,“八”,“九”};

/*** Transformer/Mutator Methods ***/

public String writeNumber(String phrase)    {         / **局部变量** /

  phrase = phrase.trim();

  /*** Counts through the length of phrase ***/

    for ( int i = 0; i < phrase.length(); i++ )
    {

     /*** If current char is a number, count through the array
          that contains the number chars until the one needed is
          found. ***/

        if ( isNumber( phrase.charAt( i ) ) )
        {
            boolean keepSearching = true;

            int j = 0;

            do
            {
               if ( numberChar[ j ] == phrase.charAt( i ) )
                  keepSearching = false;

               else
                  j++; // Increments j if char doesn't match array element

            } while ( keepSearching && j < numberChar.length );

            /*** Replaces the current char with the corresponding String
                 word from the other number array.  ***/

            phrase = phrase.replace( Character.toString(
                                      phrase.charAt( i ) ) ,
                                      numberWord[ j ] + "-" );
    }
    }

    /*** Gets rid of dashes from unwanted places ***/

    phrase = phrase.replaceAll( "- " , " " );
    phrase = phrase.replaceAll( "-," , ", " );
    phrase = phrase.replace( "-." , "." );

    if ( phrase.charAt( phrase.length() - 1 ) == '-' )
       phrase = phrase.substring( 0 , phrase.length() - 1 );

  return phrase;
}

/*** Observer Methods ***/

public boolean isNumber(char input)    {         boolean isNumber = false; //最初失败

    for ( int i = 0; i < numberChar.length; i++ )
    {
        /*** If input matches a number char, method returns true ***/

        if ( input == numberChar[ i ] )
           isNumber = true;
    }

    return isNumber;
}