Increment a string with letters?

前端 未结 12 1277
礼貌的吻别
礼貌的吻别 2021-02-08 12:35

I need to increment a string from.. let\'s say aaa to zzz and write every incrementation in the console (is incrementation even a word?). It would go s

12条回答
  •  礼貌的吻别
    2021-02-08 13:11

    Assuming you will always have 3 letters (or any other set number of letters), off the top of my head I would think to:

    Have separate variables for each letter, so instead of:

    string = "aaa";
    

    Have:

    string1 = "a";
    string2 = "a";
    string3 = "a";
    

    Then increment the one you need at each iteration. This will take a little trial and error probably, and looks like you're going from the right over to the left, so roughly:

    if(string3 != "z"){
        // Increment string 3 by a letter
    }else if(string2 != "z"){
        // Increment string 2 by a letter
    }else if (string1 != "z"){
        // Increment string 1 by a letter
    }else{
        // What ever you want to do if "zzz"
    }
    

    I didn't test that but it would be something close.

    Then

    string = string1 + string2+ string3
    

    Now you are left with a single variable like before which you can do what you intended with (i.e. output etc.)

    You could also do this with a string array, which would make it easier to have a changing amount of letters, and would need a little more code to count the array length and stuff, but I'd want to get it working at least statically first like above.

提交回复
热议问题