Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
964 views
in Technique[技术] by (71.8m points)

replace - Java - Replacing word with assigned numbers

I would like to make this code shorter and cleaner. This code works properly, but It is to long for me:

            String givenWord = "help";

           
            String partA = givenWord.replace("a", "1");
            String partB = partA.replace("b", "2");
            String partC = partB.replace("c", "10");
            String partD = partC.replace("d", "11");
            String partE = partD.replace("e", "12");
            String partF = partE.replace("f", "20");
            String partG = partF.replace("g", "21");
            String partH = partG.replace("h", "22");
            String partI = partH.replace("i", "100");
            String partJ = partI.replace("j", "101");
            String partK = partJ.replace("k", "102");
            String partL = partK.replace("l", "110");
            String partM = partL.replace("m", "111");
            String partN = partM.replace("n", "112");
            String partO = partN.replace("o", "120");
            String partQ = partO.replace("q", "121");
            String partP = partQ.replace("p", "122");
            String partR = partP.replace("r", "200");
            String partS = partR.replace("s", "201");
            String partT = partS.replace("t", "202");
            String partU = partT.replace("u", "210");
            String partV = partU.replace("v", "211");
            String partW = partV.replace("w", "212");
            String partX = partW.replace("x", "220");
            String partY = partX.replace("y", "221");
            String partZ = partY.replace("z", "222");

            System.out.println(partZ);

I need to replace all letters in the given word like that: The output is 2220110122.

I have tried to use 'for loops' and other methods, but they didn't work well. I am a beginner, that's why I am asking here :)

question from:https://stackoverflow.com/questions/65918389/java-replacing-word-with-assigned-numbers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...