猿问

Java:如何将 int 添加到字母数字字符串中的数字并返回输出

尝试将字母数字字符串中的数字增加一个数字 n 并返回结果,增加的数字位于字符串索引中的相同位置。如果数字为 9,则输出应换行为 0、1、2、3、.... 等到 9 `即 String input = "abc123de45" n = 2 print = "abc345de67"


for (int i = 0; i < this.inputString.length(); i++) {

    char tempInp = this.inputString.charAt(i);


            if (Character.isDigit(tempInp)) {

                sumDigit = tempInp + n;

            }

            }



        }  

    return sumDigit;

    }


青春有我
浏览 181回答 2
2回答

红糖糍粑

您可以使用 a 的组合StringBuilder并将其转换char为相关int值String inputString = "abc123de45";int n = 2;StringBuilder buf = new StringBuilder ();for (int i = 0; i < inputString.length(); i++) {&nbsp; &nbsp; char tempInp = inputString.charAt(i);&nbsp; &nbsp; if (Character.isDigit(tempInp)) {&nbsp; &nbsp; &nbsp; &nbsp; buf.append ((tempInp -'0') + n);&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; buf.append(tempInp);&nbsp; &nbsp; }&nbsp; &nbsp;}System.out.println(buf.toString());输出abc345de67

慕斯709654

当 if 语句为真时,您可以尝试使用 StringBuilder 更新字符串。public static StringBuilder numericInt(String a,int b){&nbsp; &nbsp; StringBuilder c = new StringBuilder(a);&nbsp; &nbsp; for (int i = 0; i < c.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; char tempInp = c.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; if (Character.isDigit(tempInp)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int temp=(c.charAt(i)-'0')+b;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.setCharAt(i,(char)(temp+'0'));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; return c;&nbsp; &nbsp; }&nbsp;&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答