How to Escape Character Sequences on a String in MATLAB

Mehak Mubarik Feb 02, 2024
  1. Special Escape Sequence Characters Supported for Non-printing Characters in MATLAB
  2. Escape Character Before Special Characters in a String in MATLAB
How to Escape Character Sequences on a String in MATLAB

We will look at different ways to escape character sequences in MATLAB string.

We will use different example codes and related outputs to clear your concepts and give you complete insight.

Note that escape character normally in other languages such as C is a backslash \. Escape character sequences are used to define operations like value returns and spacing (tab-motions).

They are frequently utilized to offer exact depictions of non-printing characters sequences and special symbols, like the single quote mark '.

In MATLAB, a backslash \ informs the system that the succeeding command is a TeX command.

The escape character sequence for MATLAB is a single quotation mark ' and sprintf(), which allows special escape sequences in other programming languages, including C, C++, etc.

Let us look first at special escape character sequences then understand the purpose of the sprintf function in supporting the escape sequences.

Special Escape Sequence Characters Supported for Non-printing Characters in MATLAB

The following table enlists the special escape character sequences supported for non-printing characters in MATLAB.

Special Character Table

Escape Character Before Special Characters in a String in MATLAB

As mentioned earlier, there are different escape sequences in MATLAB and other programming languages. MATLAB allows using ' single quotation marks as an escape character in a string.

Let us understand this concept by looking at the following example.

special_characters = '[]{}()=''.()..{%}...,;:%%!@';

tString = 'Hola, I'm a Big fan ( not the craziest though ) of MATLAB; I love % to program in MATLAB!';

outString = '';
for l = tString
    if (length(find(special_characters == l)) > 0)
        outString = [outString, '\n', l];
    else
        outString = [outString, l];
    end
    sprintf(outString)
end

Output:

ans = 'Hola, I'm a Big fan ( not the craziest though ) of MATLAB; I love'

This code is designed to print characters to a new line every time the special characters occur in a string.

By following the table of special characters given above, we can easily add escape characters in our string according to the need.

Mehak Mubarik avatar Mehak Mubarik avatar

Mehak is an electrical engineer, a technical content writer, a team collaborator and a digital marketing enthusiast. She loves sketching and playing table tennis. Nature is what attracts her the most.

LinkedIn

Related Article - MATLAB Character

Related Article - MATLAB String