1
$\begingroup$

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.)

{"a3bykmn","oka2bcka","bdkba1","4ckxyz"}

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

{a2bykmn,oka1bcka,bdkba0,3ckxyz} 

Nevertheless, answer provided by the experts helpful.

$\endgroup$
2
  • $\begingroup$ Can you please include some code that you have written so far? Have you asked your instructor for clarification? $\endgroup$
    – Syed
    Sep 11, 2021 at 5:05
  • $\begingroup$ @Syed Also raised a query with the instructor (community.wolfram.com/groups/-/m/t/2365003). $\endgroup$ Sep 11, 2021 at 5:17

1 Answer 1

3
$\begingroup$
lst = {"a3bykmn", "oka2bcka", "bdkba1", "4ckxyz"}; 

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

and

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
"3c-4kx-1y-10001z"
StringReplace[p : DigitCharacter .. :> ToString[-1 + ToExpression @ p]] @ str 
"3c-2kx-1y-9999z"
$\endgroup$
2
  • 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, privacy policy and cookie policy

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