在Matlab中,在字符串中大写/大写每个单词的第一个字母的最佳方法是什么?
即
西班牙的雨主要落在飞机上。
至
西班牙瀑布的雨主要在飞机上
发布于 2010-02-23 14:58:37
所以使用字符串
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)}')发布于 2010-02-23 14:51:48
由于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代码取自这堆栈溢出问题。
发布于 2010-02-23 13:14:55
大量的方式:
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)更优雅/更复杂的--单元格数组、文本扫描和单元格有趣--对于这类事情非常有用:
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
endhttps://stackoverflow.com/questions/2317817
复制相似问题