英文:
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('0', '5'); //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 = "0000123";
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 = "0000123";
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论