Java中的问题:替换字符。

huangapple go评论112阅读模式
英文:

Problem having on Java; replace the character

问题

public static int conversion(int n) {

    String str = Integer.toString(n);    // 将整数转换为字符串
    String str1 = str.replaceAll("^0+", ""); // 替换字符串中以0开头的部分
    str1 = str1.replace('0', '5'); // 替换字符串中的0为5
    int result1 = Integer.parseInt(str1); // 将字符串转换为整数

    int result = result1;

    return result;
}

我正在尝试将字符从'0'替换为'5'。当前的代码只能在字符串开头没有'0'时正常工作。

例如:'50005' -> '55555'(可以);'00005000' -> '5555'(不可以)<-开头的'0'没有改变。

要修复此错误,您可以使用上面修改过的代码。

英文:
public static int conversion(int n) {

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

    int result = result1;

    return result;


}

I'm trying to replace the character from '0' to '5'.
The current code works, but only when there is no '0' at the front.

example: '50005' -> '55555' (o) ; '00005000' -> '5555' (x) <-front '0' didn't change

What should I add or know to fix this error?

答案1

得分: 0

Leading zeroes on ints are ignored in the conversion process.

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

Prints

0000123
123

If you prefix a 0 to an int, it treats it as an octal value and ignores the zeros.

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

Prints

25
25
英文:

Leading zeroes on ints are ignored in the conversion process.

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

Prints

0000123
123

If you prefix a 0 to an int, it treats it as an octal value and ignores the zeros.

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

Prints

25
25


</details>



huangapple
  • 本文由 发表于 2020年7月22日 05:45:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63023576.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定