7.6: Counting Characters- strlength vs. length

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    7.6: Counting Characters- strlength vs. length

    MATLAB has both strlength and length, and they do not always answer the same question. This is an important beginner detail.

    Exercise \(\PageIndex{1}\)
    % Run the following commands and notice what MATLAB returns.
    
    strlength('Hello World')
    
    strlength("Hello World")
    
    length('Hello World')
    
    length("Hello World")

    The function strlength counts the number of characters in text. The function length behaves more like an array-size function. For a character vector, length returns the number of characters. For a string scalar, length returns the number of string elements, which is 1.

    Expression

    What it measures

    Expected idea

    strlength('Hello World')

    Characters in the text

    11

    strlength("Hello World")

    Characters in the string

    11

    length('Hello World')

    Number of elements in the character vector

    11

    length("Hello World")

    Number of elements in the string array

    1

    Note

    Use strlength when you want to count characters in text. Use length when you are thinking about array size.


    This page titled 7.6: Counting Characters- strlength vs. length was last modified on Tue, 30 Jun 2026 02:11:53 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.