在Java中将子字符串中的数字转换为单词

3
我是一个 Java 新手。我想将字符串中特定位置的数字子串转换为英文单词。例如,给定字符串 ABC12345DEFG 和子串 substring(3,8),输出结果应为:
ABConetwothreefourfiveDEF

我尝试使用以下代码,但它只返回了ABCfiveDEFG。您能帮我解决这个问题吗?
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);

作为一个副话题,最好只依赖ASCII码并映射到字符串数组中的单词,这样你就可以在O(n)时间内完成,而不是O(n2)。 - Alex Suo
所以,根据你的代码,你正在用words数组中的每个元素替换12345,当你想要用适当的单词替换单个数字时 - 所以你的逻辑从一开始就是错误的。也许使用StringBuilder来存储结果,从str中取出每个字符,检查它是否为数字,然后将结果附加到StringBuilder中。 - MadProgrammer
5个回答

1

1) 你不应该替换所有的substring(3,8),因为你真正想要的是一次只替换一个字符。

2) 每次循环到时,你的代码都会改变newStr。最后一次是针对5的,这就是为什么你只得到了"ABCfiveDEFG"。

3) 循环遍历数组以查找与i相等的索引是有点奇怪的吗?如果j==i,那么就使用i,确保它在范围内。

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);

1
尝试像这样做一些事情:

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;
}

这样调用:

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

返回这个:

ABConetwothreefourfiveDEF


1
一些你可以改进的地方是:

  1. Change

    String words = {"zero", "one", "two", "three", "four", "five"};
    

    to

    String[] words = new String[]{"zero", "one", "two", "three", "four", "five"};
    
这是一个字符串数组,这是一种正确的表示方式。
  1. In your loop, change

    if (i==j){
        newStr = str.replace(str.substring(3,8), words[j];
    }
    

    to

    if (i == j) {
        newStr = str.replace(Character.toString(c), words[j]); // replace the numeric character with equivalent string
        str = newStr; // update the base string
     }
    
你试图用数组中的一个字符串替换整个数字字符子串。

0

你的代码逻辑有误

尝试一种更简单的方法

    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 >= 1 && i <= 5) // or (words.length - 1)
        {
            newStr += words[i];
        }
        else {
            newStr += c;
        }
    }
    System.out.println(newStr);

输出

ABConetwothreefourfiveDEFG

0

其他人给他代码,但没有指出他代码中的错误。这对他来说不是很好,因为他正在学习新语言。我会在下面指出内联注释:

String str = "ABC12345DEFG";
String newStr = "";
String words = {"zero", "one", "two", "three", "four", "five"}; // Im not recommend to declare this defination because this data as a library. So you should map them as: 1->one, 2->two,... IF you just define as array, if the index is wrong => the data will be wrong
for (char c:str.toCharArray()){
    int i = (int)(c-'0'); // Should not declare variable inside the loop
    for (int j=0; j<words.length; j++){ // There are 2 loop => O(n2) => bad performance
        if (i==j){
            newStr = str.replace(str.substring(3,8), words[j]; // Wrong replace here, that why the final result is wrong
        }
    }
}
System.out.println(newStr);

我的代码不是最好的,但我相信它具有良好的性能和清晰的定义。

public static void main(String[] args){
    String str = "ABC12345DEFG";
    Map<Integer, String> numberInWord = new ConcurrentHashMap<Integer, String>(5) {{
    put(0,"zero"); put(1,"one"); put(2,"two"); put(3,"three"); put(4,"four"); put(5,"five");
    }};
    for(Map.Entry<Integer, String> entry : numberInWord.entrySet()){
        str = str.replace(entry.getKey().toString(), entry.getValue());
    }
    System.out.println(str);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接