Filter löschen
Filter löschen

Truncate strings to maximum length

90 Ansichten (letzte 30 Tage)
DNF
DNF am 16 Feb. 2023
Bearbeitet: Jan am 16 Feb. 2023
I have an array of strings (new strings, not old character arrays) of varying lengths, and I would like to truncate them to below some maximum length. I thought that extractBefore would be helpful, but it fails for strings shorter than the truncation length.
>> str = ["ab", "cdefg"];
>> extractBefore(str, 3) % this works fine
ans =
1×2 string array
"ab" "cd"
>> extractBefore(str, 4) % this fails
Error using extractBefore
Numeric value exceeds the number of characters in element 1.
This is my current solution:
>> arrayfun(@(s)extractBefore(s, min(4, s.strlength())+1), str)
ans =
1×2 string array
"ab" "cdef"
However, this is awkward and difficult to read.
Is there no ready-made functionality for doing this?

Antworten (2)

Jan
Jan am 16 Feb. 2023
Bearbeitet: Jan am 16 Feb. 2023
Omit arrayfun:
str = ["ab", "cdefg"];
extractBefore(str, min(4, str.strlength())+1)
ans = 1×2 string array
"ab" "cdef"
If this still looks to clumsy, write your own function:
limitWidth(str, 4)
function s = limitWidth(s, n)
s = extractBefore(s, min(n, s.strlength()) + 1);
end

Stephen23
Stephen23 am 16 Feb. 2023
str = ["ab", "cdefg"];
out = regexp(str,'^.{1,4}','match','once')
out = 1×2 string array
"ab" "cdef"

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by