How can I create an acronym from a string in MATLAB?

给你一囗甜甜゛ 提交于 2019-11-28 05:32:08

问题


Is there an easy way to create an acronym from a string in MATLAB? For example:

'Superior Temporal Gyrus' => 'STG'

回答1:


If you want to put every capital letter into an abbreviation...

... you could use the function REGEXP:

str = 'Superior Temporal Gyrus';  %# Sample string
abbr = str(regexp(str,'[A-Z]'));  %# Get all capital letters

... or you could use the functions UPPER and ISSPACE:

abbr = str((str == upper(str)) & ~isspace(str));  %# Compare str to its uppercase
                                                  %#   version and keep elements
                                                  %#   that match, ignoring
                                                  %#   whitespace

... or you could instead make use of the ASCII/UNICODE values for capital letters:

abbr = str((str <= 90) & (str >= 65));  %# Get capital letters A (65) to Z (90)


If you want to put every letter that starts a word into an abbreviation...

... you could use the function REGEXP:

abbr = str(regexp(str,'\w+'));  %# Get the starting letter of each word

... or you could use the functions STRTRIM, FIND, and ISSPACE:

str = strtrim(str);  %# Trim leading and trailing whitespace first
abbr = str([1 find(isspace(str))+1]);  %# Get the first element of str and every
                                       %#   element following whitespace

... or you could modify the above using logical indexing to avoid the call to FIND:

str = strtrim(str);  %# Still have to trim whitespace
abbr = str([true isspace(str)]);


If you want to put every capital letter that starts a word into an abbreviation...

... you can use the function REGEXP:

abbr = str(regexp(str,'\<[A-Z]\w*'));



回答2:


thanks, also this:

s1(regexp(s1, '[A-Z]', 'start'))

will return abbreviation consisting of capital letters in the string. Note the string has to be in Sentence Case



来源:https://stackoverflow.com/questions/3038768/how-can-i-create-an-acronym-from-a-string-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!