Function Repository Resource:

StringSwitch

Source Notebook

Switch but for strings

Contributed by: Michael Sollami

ResourceFunction["StringSwitch"][string,form1,value1,form2,value2,]

compares string with each of the patterns formi in turn, evaluates, and returns the valuei corresponding to the first match found.

Details and Options

ResourceFunction["StringSwitch"] uses StringMatchQ to compare the first argument to the formi, rather than MatchQ.
The catch-all default form should be BlankNullSequence.

Examples

Basic Examples (3) 

Switch on a string, just like you have always wanted to:

In[1]:=
ResourceFunction[
 "StringSwitch"]["123!", __ ~~ "#", 1, __ ~~ "!", 2, __ ~~ "#", 3]
Out[1]=

Switch using any valid string pattern:

In[2]:=
ResourceFunction["StringSwitch"][#, NumberString .., "numbers", "t" ~~ __ ~~ "a", "genius"] & /@ {"tesla", "1234"}
Out[2]=

Provide a default case:

In[3]:=
ResourceFunction["StringSwitch"][#, x__ /; StringStartsQ[x, "x"], "Starts with x", ___, "Doesn't start with x"] & /@ {"xyz", "zyx"}
Out[3]=

Possible Issues (2) 

The first argument must be a String:

In[4]:=
ResourceFunction["StringSwitch"][123, ___, True]
Out[4]=

StringSwitch takes an odd number of arguments:

In[5]:=
ResourceFunction["StringSwitch"]["123", ___, True, ___]
Out[5]=

Publisher

Michael Sollami

Version History

  • 1.0.0 – 25 February 2020

License Information