strncmp

Compares the first n characters of two texts, case sensitive.

Category: Language Fundamentals > Data Types

Syntax

tf = strncmp(s1, s2, n)

Returns true if the first n characters are the same.

Description

strncmp is the prefix version of strcmp. If either text is shorter than n characters the result is false, even if the shorter text is a prefix of the other.

With a cell array, each element is tested against the other argument, so one call classifies a list by its beginnings.

Input arguments

s1, s2
Character vectors, strings, cell arrays or string arrays.
n
Positive integer: how many characters to compare.

Output arguments

tf
Logical scalar or array.

Example

Prefix comparison

strncmp('abcdef', 'abcxyz', 3)
strncmp({'abc','abd'}, 'abx', 2)
strncmp('abc', 'abd', 5)
Output
ans = logical
   1
ans = 1×2 logical array

   1   1
ans = logical
   0

See also

strcmp strncmpi startsWith strcmpi