更改数字 java

Change digit in a number java

我正在尝试执行下一个代码:它将有一个字符串“00000”,并且必须一直持续到“99999”,每次当其中一个字符为 3 时,它将被 'E',并打印出来。例如'00003'->'0000E'

我正在尝试执行 for 循环,但我不知道如何执行 "count"(00000,00001,00002 等)

你能帮帮我吗?谢谢!

在所有情况下,数据保持整数类型:

for (int n = 0; n <= 99999; ++n)/*etc*/
  1. 逃避方式:使用您最喜欢的数字格式化程序将 n 转换为带前导零的字符串 class。将每个“3”替换为 'E'.

  2. 可爱的方式:实现您自己的数字格式化程序并使用它来显示 n

这两种方法都比对字符串进行实际计数更优雅。不要混用 datapresentation.

这就是我要解决的方法。

for( int i = 0 ; i < 100000 ; ++i) {
    String my_str = String.format("%05d", i);
    String my_new_str = my_str.replaceAll("3", "E");
    System.out.prinln(my_new_str);
}

正如其他一些回复所说,您应该使用 for 使用 int 类型作为数字

for (int i = 0; i < 99999; i++)
{
   // fill the number with zeros (if needed) and then it will replace the "3" with "E"
   System.out.println(ldap(i+"").replace("3", "E")); 
}

然后创建一个 lpad 函数,用于填充剩余的 space 如果长度与所需长度不同...

即。你想要所有数字长 4 位数字,数字 11 有 2 个字符的长度,那么你必须在前面加上 2 个字符 0

public static String ldap(String prop)
{
    while(prop.length() < 4)  // continue until the length is less then 4 (or the length desired)
    {
        prop = "0"+prop;  // prepend the character '0' to the number
    }
    return prop;
}

用“E”替换所有“3”

public static String replace3WithE(String s) {
    return ("" + s).replaceAll("3", "E");
}