繁体   English   中英

在Matlab中将字符串中每个单词的首字母大写/大写?

[英]Capitalize / Capitalise first letter of every word in a string in Matlab?

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


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

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

所以使用字符串

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.

\\<[az]匹配每个单词的第一个字符,您可以使用${upper($1)}将其转换为大写

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

regexprep(str,'(\<\w)','${upper($1)}')

由于Matlab带有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代码取自 Stack Overflow问题。

大量的方式:

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
    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

不那么优雅和高效,更易读和可维护。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM