代码之家  ›  专栏  ›  技术社区  ›  Rook

在matlab中,是否将字符串中每个单词的第一个字母大写/大写?

  •  7
  • Rook  · 技术社区  · 15 年前

    在matlab中,将每个单词的第一个字母大写/大写的最佳方法是什么?


    西班牙的雨主要落在飞机上

    西班牙的雨主要落在飞机上

    4 回复  |  直到 15 年前
        1
  •  21
  •   Adrian    15 年前

    所以使用字符串

    str='the rain in spain falls mainly on the plain.'
    

    只需在matlab中使用regexp替换函数,regexprep

    regexprep(str,'(\<[a-z])','${upper($1)}')
    
    ans =
    
    The Rain In Spain Falls Mainly On The Plain.
    

    这个 \<[a-z] 匹配每个单词的第一个字符,您可以使用 ${upper($1)}

    这也可以用 \<\w 匹配每个单词开头的字符。

    regexprep(str,'(\<\w)','${upper($1)}')
    
        2
  •  2
  •   Community CDub    8 年前

    因为Matlab附带 build in Perl 对于每个复杂的字符串或文件处理任务,可以使用Perl脚本。所以你可以用这样的方法:

    [result, status] = perl('capitalize.pl','the rain in Spain falls mainly on the plane')
    

    其中capitalize.pl是一个Perl脚本,如下所示:

    $input  = $ARGV[0];
    $input =~ s/([\w']+)/\u\L$1/g;
    print $input;
    

    Perl代码取自 this 堆栈溢出问题。

        3
  •  1
  •   Nivag    15 年前

    负载方式:

    str = 'the rain in Spain falls mainly on the plane'
    
    spaceInd = strfind(str, ' '); % assume a word is preceded by a space
    startWordInd = spaceInd+1;  % words start 1 char after a space
    startWordInd = [1, startWordInd]; % manually add the first word
    capsStr = upper(str);
    
    newStr = str;
    newStr(startWordInd) = capsStr(startWordInd)
    

    更优雅/更复杂的——单元格数组、文本扫描和CellFun对于这种事情非常有用:

    str = 'the rain in Spain falls mainly on the plane'
    
    function newStr = capitals(str)
    
        words = textscan(str,'%s','delimiter',' '); % assume a word is preceded by a space
        words = words{1};
    
        newWords = cellfun(@my_fun_that_capitalizes, words, 'UniformOutput', false);
        newStr = [newWords{:}];
    
            function wOut = my_fun_that_capitalizes(wIn)
                wOut = [wIn ' ']; % add the space back that we used to split upon
                if numel(wIn)>1
                    wOut(1) = upper(wIn(1));
                end
            end
    end
    
        4
  •  1
  •   Emilio M Bumachar    15 年前
        str='the rain in spain falls mainly on the plain.' ;
    for i=1:length(str)
        if str(i)>='a' && str(i)<='z'
            if i==1 || str(i-1)==' '
                str(i)=char(str(i)-32); % 32 is the ascii distance between uppercase letters and its lowercase equivalents
            end
        end
    end
    

    更少的Elegant和高效,更可读和可维护。