Wolfram Mathematica

Flexible String Processing

Version 11 adds a variety of low-level functions that allow flexible manipulation of strings.

Take a string containing a sequence of personal details.

In[1]:=
```string = "lastname Doe firstname John age 20 email john.doe@mail.com \ mobile 123-456-7890";```

Construct a list of substrings with StringSplit.

In[2]:=
`splitstring = StringSplit[string]`
Out[2]=

Pad all substrings with spaces on the right to make them be of length 20.

In[3]:=
`padstring = StringPadRight[splitstring, 20, " "]`
Out[3]=

Partition the resulting expression to group strings by details.

In[4]:=
`partstring = Partition[padstring, 2]`
Out[4]=

Use StringRiffle to concatenate all strings, inserting newlines between groups and empty strings within each group.

In[5]:=
`rifstring = StringRiffle[partstring, "\n", ""]`
Out[5]=

The final expression is a String object.

In[6]:=
`Head[rifstring]`
Out[6]=

An alternative way of inserting newlines is using the function InsertLinebreaks.

In[7]:=
`StringTake[ExampleData[{"Text", "AliceInWonderland"}], 200]`
Out[7]=
In[8]:=
```StringTake[ExampleData[{"Text", "AliceInWonderland"}], 200]; InsertLinebreaks[%, 40]```
Out[8]=