How do you get up to first n characters in a string?
조회 수: 410 (최근 30일)
이전 댓글 표시
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?
댓글 수: 1
Stephen23
2024년 2월 2일
You were very close:
s_arr = ["a";"ab";"abc";"abcd";"abcde"]
cellfun(@(s) s(1:min(end,3)), s_arr, 'uni',0)
답변 (4개)
Dyuman Joshi
2024년 2월 2일
s_arr = ["a";"ab";"abc";"abcd";"abcde";"abcdef";"xyzxyzxyz"]
pos = 4; % pos = no. of characters + 1
extractBetween(s_arr, 1, min(pos, strlength(s_arr)))
댓글 수: 0
Paul
2021년 10월 27일
편집: Paul
2024년 2월 2일
If a string array:
s_arr = ["a";"ab";"abc";"abcd";"abcde"]
s_arr(strlength(s_arr)>3) = extractBefore(s_arr(strlength(s_arr)>3),4)
Exact same code works on a cell array
s_arr = cellstr(["a";"ab";"abc";"abcd";"abcde"])
s_arr(strlength(s_arr)>3) = extractBefore(s_arr(strlength(s_arr)>3),4)
댓글 수: 1
Image Analyst
2021년 10월 26일
% 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
Image Analyst
2021년 10월 26일
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))
Ramanan
2024년 2월 2일
You can use the extractBefore function in the array function instead.
pos = 4; % pos = no. of characters + 1
out = arrayfun(@(s) extractBefore(s,pos), s_arr);
댓글 수: 2
Ramanan
2024년 2월 2일
You can add the min function and make use of the length of the string inside the arrayfun.
I don't notice the previously answered one.
s_arr = ["a";"ab";"abc";"abcd";"abcde";"abcdef";"xyzxyzxyz"];
pos = 4; % pos = no. of characters + 1
out = arrayfun(@(s) extractBefore(s,min(pos,strlength(s))), s_arr)
Also I think a more simplified version is submitted by Dyuman Joshi.
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!