Wolfram Language

Text & Language Processing

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]:=
Click for copyable input
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]:=
Click for copyable input
splitstring = StringSplit[string]
Out[2]=

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

In[3]:=
Click for copyable input
padstring = StringPadRight[splitstring, 20, " "]
Out[3]=

Partition the resulting expression to group strings by details.

In[4]:=
Click for copyable input
partstring = Partition[padstring, 2]
Out[4]=

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

In[5]:=
Click for copyable input
rifstring = StringRiffle[partstring, "\n", ""]
Out[5]=

The final expression is a String object.

In[6]:=
Click for copyable input
Head[rifstring]
Out[6]=

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

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

Related Examples

de es fr ja ko pt-br zh