【问题标题】:Problem having on Java; replace the characterJava有问题;替换字符
【发布时间】:2020-07-21 21:45:29
【问题描述】:
public static int conversion(int n) {

    String str = Integer.toString(n);    //int to string
    String str1= str.replace('0', '5'); //replace the character in string
    int result1 = Integer.parseInt(str1); //string to int

    int result = result1;

    return result;


}

我正在尝试将字符从“0”替换为“5”。 当前代码有效,但前提是前面没有'0'。

示例:'50005' -> '55555' (o) ; '00005000' -> '5555' (x)

我应该添加什么或知道什么来修复这个错误?

【问题讨论】:

  • 因为 55500000555相同的数字,根据数学。
  • Integer.toString 永远不会返回带有前导零的字符串。 int 文字 00005000 实际上是八进制表示,将被解释为 2560 -> conversion(00005000) 等于 conversion(2560) 并将返回 2565

标签: java string replace


【解决方案1】:

在转换过程中忽略整数的前导零。

String str = "0000123";
int n = Integer.valueOf(str);
System.out.println(str);
System.out.println(n);

打印

0000123
123

如果您在 int 前面加上 0,它会将其视为八进制值并忽略零。

int octalVal = 000031;
System.out.println(octalVal);
String decimalStringVal = Integer.toString(octalVal);
System.out.println(decimalStringVal);

打印

25
25

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2013-05-04
    • 2010-10-04
    • 2015-10-11
    • 2011-11-24
    • 1970-01-01
    相关资源
    最近更新 更多