Select part of a string

139 ビュー (過去 30 日間)
JE101
JE101 2017 年 3 月 23 日
コメント済み: Gina Eldridge 2022 年 4 月 4 日
I have a large column vector of strings. The strings vary in length. I would like to select out the last 5 characters of the actual string (i.e., I don't want 5 blank spaces that you would get by converting it to a char array and then selecting the last 5 columns).
I have a complicated way of doing this by switching between a string array and a character array and using sub2ind, but I was wondering if there is a simpler way to do this. I've tried using strtok and flip, but can't get it to do exactly what I want.
If possible, I'd like to avoid using a loop (because of the size of the array).
If you use excel, I want to do the equivalent of the RIGHT function.
Any suggestions would be much appreciated! Thanks.

採用された回答

Stephen23
Stephen23 2017 年 3 月 23 日
編集済み: Stephen23 2017 年 3 月 23 日
A string array treats each string as being atomic, whereas you need to be able to access each character as atomic. Use cellstr to convert to a cell array of chars, and then use cellfun to extract the parts you need:
cellfun(@(s)s(end-4:end),cellstr(inp),'uni',0)
  1 件のコメント
JE101
JE101 2017 年 3 月 23 日
Perfect! Thanks Stephen.

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2017 年 3 月 23 日
Another approach, if you're using the string class introduced in release R2016b, is to use extractAfter.
>> animals = {'cat'; 'elephant'; 'dog'; 'hippopotamus'};
>> animalsString = string(animals);
>> lastTwoLetters = extractAfter(animalsString, strlength(animalsString)-2)
lastTwoLetters =
4×1 string array
"at"
"nt"
"og"
"us"
  2 件のコメント
JE101
JE101 2017 年 3 月 23 日
That's great. Thanks Steven.
Gina Eldridge
Gina Eldridge 2022 年 4 月 4 日
love it

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by