Use StringReplace with RuleDelayed to replace each integer digit character in the following strings with a digit that is 1 less than the number represented by the digit character. (Hint: Use DigitCharacter, ToString and ToExpression.)


The solution provided by the instructor is:

Output: {a3bykmn,oka2bcka,bdkba1,4ckxyz}

I think either there is typographical error with the solution provided or I am missing something. The only difference between the input and output is removal of "" with the strings.

To the best of my understanding, what the problem demands is conversion of integers to 1 less. For instance, "a3bykmn" will have a2bykmn as output.The Set Delayed will ensure the output as a1bykmn the next time. But what after a0bykmn. Will it be a-0bykmn?

On refreshing the notebook,indeed the expected output is


Nevertheless, answer provided by the experts helpful.


1 Answer 1

lst = {"a3bykmn", "oka2bcka", "bdkba1", "4ckxyz"}; 

StringReplace[ns : NumberString :> ToString[-1 + ToExpression @ ns]] @ lst
{"a2bykmn", "oka1bcka", "bdkba0", "3ckxyz"}


StringReplace[dc : DigitCharacter .. :> ToString[-1 + ToExpression @ dc]] @ lst
{"a2bykmn", "oka1bcka", "bdkba0", "3ckxyz"}

Note the difference:

str = "4c-3kx0y-10000z";

StringReplace[p : NumberString :> ToString[-1 + ToExpression @ p]] @ str
StringReplace[p : DigitCharacter .. :> ToString[-1 + ToExpression @ p]] @ str 
  • 1
    $\begingroup$ DigitCharacter does not take into account arithmetical operators (+ or -) with it? $\endgroup$ Sep 11, 2021 at 5:44
  • $\begingroup$ @SplendidDigitalSolutions, your are right. $\endgroup$
    – kglr
    Sep 11, 2021 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.