Message Boards Message Boards

0
|
3619 Views
|
4 Replies
|
1 Total Likes
View groups...
Share
Share this post:

StringReplace with conditionals

Posted 4 years ago

Hey all, can anybody please help me out here? Why does the following line not replace every character that appears more than once in the string?

str = "AAbCC";
StringReplace[str, c_ -> "X" /; StringCount[str, c] > 1]

Does anyone have a more elegant solution? Still learning Mathematica, sorry...

Thank you and all the best Timo

POSTED BY: Timo Kuchheuser
4 Replies

For anyone interested. Here's my complete code. From time to time I try to solve exercises from codewars in different languages.

This one is based on this one https://www.codewars.com/kata/54b42f9314d9229fd6000d9c

On[Assert];
singleEncode = "(";
doubleEncode = ")";
distinctChars = "ABCDE";
distinctCharsMixed = "AbCdE";
doubledChars = "AABBCCDDEE";
doubledCharsMixed = "AabBCcDdEe";

encodeString[s_String] := 
  StringReplace[
   s, {(c_ /; (StringCount[s, c, IgnoreCase -> True] > 1) -> 
      doubleEncode), (c_ -> singleEncode)}];

Assert[encodeString[distinctChars] == "((((("]
Assert[encodeString[distinctCharsMixed] == "((((("]
Assert[encodeString[doubledChars] == "))))))))))"]
Assert[encodeString[doubledCharsMixed] == "))))))))))"]
POSTED BY: Timo Kuchheuser
Posted 4 years ago

Alternatively you can do it this way:

StringReplace[str, c_ ~~ c_ -> "XX"]
POSTED BY: Michael Helmle

Thank you!

POSTED BY: Timo Kuchheuser

Got it. Once you do it right, it works ;)

StringReplace[str, c_ /; (StringCount[str, c] > 1) -> "X"]
POSTED BY: Timo Kuchheuser
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract