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);
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With