Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numbers in substring to words in java

Tags:

java

string

I'm novice to java. I want to convert numbers in substring to English words with certain position in a string.

For example, the string ABC12345DEFG and substring(3,8) should output the following.

ABConetwothreefourfiveDEF

I tried with the following code but it only returned ABCfiveDEFG. Could you help me solve this problem?

String str = "ABC12345DEFG";
String newStr = "";
String words = {"zero", "one", "two", "three", "four", "five"};
for (char c:str.toCharArray()){
    int i = (int)(c-'0');
    for (int j=0; j<words.length; j++){
        if (i==j){
            newStr = str.replace(str.substring(3,8), words[j];
        }
    }
}
System.out.println(newStr);
like image 229
mdfox Avatar asked Dec 07 '25 22:12

mdfox


2 Answers

1) You shouldn't be replacing all of substring(3,8), since you really just want to replace one character at a time.

2) Your line is changing newStr each time it hits. The final time is for 5, which is why you only have "ABCfiveDEFG"

3) Looping through the array to find an index that is equal to i is...weird? If j==i, then just use i, making sure it is in range.

String str = "ABC12345DEFG";
String newStr = "";
String words = {"zero", "one", "two", "three", "four", "five"};
for (char c:str.toCharArray()){
    int i = (int)(c-'0');
    if (i >= 0 && i < words.length)
        newStr += words[i];
    else
        newStr += c;
}
System.out.println(newStr);
like image 130
Garr Godfrey Avatar answered Dec 10 '25 12:12

Garr Godfrey


Try something like this:

public static String exchange( final String txt, final String... numbers ) {
    String result = txt;
    for ( int i = 0; i < numbers.length; ++i ) {
        result = result.replace( Integer.toString( i ), numbers[i] );
    }
    return result;
}

Called like this:

exchange( "ABC12345DEF", "zero", "one", "two", "three", "four", "five" )

Returns this:

ABConetwothreefourfiveDEF

like image 35
Usagi Miyamoto Avatar answered Dec 10 '25 11:12

Usagi Miyamoto