【问题标题】:How can I create an acronym from a string in MATLAB?如何从 MATLAB 中的字符串创建首字母缩写词?
【发布时间】:2010-06-14 16:06:06
【问题描述】:

有没有一种简单的方法可以在 MATLAB 中从字符串创建首字母缩写词?例如:

'Superior Temporal Gyrus' => 'STG'

【问题讨论】:

    标签: regex string matlab acronym


    【解决方案1】:

    如果你想把每个大写字母都变成缩写......

    ...你可以使用函数REGEXP:

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

    ...或者您可以使用函数UPPER 和ISSPACE:

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

    ... 或者您也可以使用 ASCII/UNICODE values 作为大写字母:

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


    如果你想把单词开头的每个字母都变成缩写...

    ...你可以使用函数REGEXP:

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

    ...或者您可以使用函数STRTRIM、FIND 和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
    

    ...或者您可以使用logical indexing 修改上述内容以避免调用FIND:

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


    如果你想把一个单词开头的每个大写字母都变成一个缩写......

    ...你可以使用函数REGEXP:

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

    【讨论】:

    • @Jonas: Wheeeeee[taptaptap]eeeeee!
    • 一个非常模糊的问题的好答案
    【解决方案2】:

    谢谢,还有这个:

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

    将返回由字符串中的大写字母组成的缩写。注意字符串必须在句子大小写中

    【讨论】:

    • 'start' 选项实际上是不必要的,因为默认情况下,从 REGEXP 返回的第一个参数将是匹配的起始索引。
    猜你喜欢
    • 2013-12-17
    • 2023-04-09
    • 2021-07-14
    • 1970-01-01
    • 2011-01-20
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多