MATLAB Answers

How do you get up to first n characters in a string?

10 views (last 30 days)
Dylan
Dylan on 26 Oct 2021
Commented: Star Strider on 27 Oct 2021
I have an array of strings of variable length s_arr. I want to limit the strings to only contain the first 3 elements. Some of the string have less than 3 elements, in which case they should be unchanged. I tried
arrayfun(@(s) s(1:3), s_arr)
but this gives an error when it finds a string with fewer than 3 elements. Why does MATLAB give an error and not just return the string unchanged? How can I achieve this goal?

Answers (3)

Image Analyst
Image Analyst on 26 Oct 2021
% Character array
charArray = 'abcdefgh' % Single quotes
n = 3
out = charArray(1:n) % Another way
% String
str = "abcdefgh" % Double quotes
n = 3
charArray = char(str)
out = charArray(1:n)
charArray =
'abcdefgh'
n =
3
out =
'abc'
str =
"abcdefgh"
n =
3
charArray =
'abcdefgh'
out =
'abc'
  1 Comment
Image Analyst
Image Analyst on 26 Oct 2021
For the case where n is longer than the string, or less than the string (so more general and robust):
% Character array
charArray = 'ab' % Single quotes
n = 30
out = charArray(1:min(length(charArray), n)) % Another way
% String
str = "ab" % Double quotes
charArray = char(str)
out = charArray(1:min(length(charArray), n))

Sign in to comment.


Star Strider
Star Strider on 26 Oct 2021
I’m not certain what the arguments are, so I can’t test this with an array, however it works with individual argument.
Perhaps:
sfcn = @(s) s(1:min(numel(s),3));
then using ‘sfcn’ in the arrayfun call will produce the desired result.
.
  4 Comments
Star Strider
Star Strider on 27 Oct 2021
My guess is that they’re actually character arrays, so the indexing in the original post, and my adaptation of it to work with character arrays that are less than 3 characters in length, would work.
.

Sign in to comment.


Paul
Paul on 27 Oct 2021
s_arr = ["a";"ab";"abc";"abcd";"abcde"]
s_arr = 5×1 string array
"a" "ab" "abc" "abcd" "abcde"
s_arr(strlength(s_arr)>3) = extractBefore(s_arr(strlength(s_arr)>3),4)
s_arr = 5×1 string array
"a" "ab" "abc" "abc" "abc"

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by