MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: a conflicting StringReplace

  • To: mathgroup at smc.vnet.net
  • Subject: [mg56335] Re: a conflicting StringReplace
  • From: "snoofly" <snoofly at snoofly.com>
  • Date: Fri, 22 Apr 2005 06:23:19 -0400 (EDT)
  • References: <d47tic$578$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

This is expected behaviour according to the doc:
StringReplace goes through a string, testing substrings that start at each 
successive character position. On each substring, it tries in turn each of 
the transformation rules you have specified. If any of the rules apply, it 
replaces the substring, then continues to go through the string, starting at 
the character position after the end of the substring.

First position a is considered to match the list of rules as given in order. 
The first rule that matches is the "ab->AB" as we are at the first position. 
We then start from character c (the character positioned after the end of 
the replaced substring. No match. Done.

Functionally more intuitive would be for the list to be processed 
iteratively L-R (possibly as another X->Iterative option):
ie. StringReplace["abc", {"ab"->"AB", "bc"->"BC"}] = "ABc" by virtue of the 
fact that after the ab transform, the string bc no longer exists.
and StringReplace["abc", {"bc"->"BC", "ab"->"AB"}] = "aBC"
and StringReplace["abc", {"ab"->"AB", "Bc"->"bC"}] = "abC"

"Hui Fang" <fangh73 at xmu.edu.cn> wrote in message 
news:d47tic$578$1 at smc.vnet.net...
>I was teaching Mathematica in a college. In the class I was showing them
> some built-in functions about strings. Since this is not a very
> important issue, I didn't spend much time on each function. When I show
> them StringReplace, I gave them the following examples:
> In[1]    StringReplace["abc",{"ab"->"AB"}]
> Out[1]   ABc
>
> In[2]   StringReplace["abc", {"bc"->"BC"}]
> Out[2]   aBC
>
> No problem on those. Now a student tried the following:
> In[3]   StringReplace["abc", {"ab"->"AB", "bc"->"BC"}]
> Out[3]   ABc
>
> Now he asked me why only "ab" is replaced. I said this is because there
> is a conflict because both "ab" and "bc" contains "b". So Mathematica
> will choose the first replacement. I also told him if he changes the
> order, he will get aBC. Now:
> In[4]    StringReplace["abc", {"bc"->"BC","ab"->"AB"}]
> Out[4]    ABc
>
> This is the part I don't understand. Does Mathematica treat those rules
> in their canonical order (since "ab" is before "bc" in canonical
> order.), or in their written order?
>
> Thanks a lot!
>
> Hui Fang
> 


  • Prev by Date: Re: removing sublist . Again and Different
  • Next by Date: Re: Re: multiple 3d plots
  • Previous by thread: Re: a conflicting StringReplace
  • Next by thread: Re: a conflicting StringReplace