在Matlab中将字符串中每个单词的第一个字母大写/大写的最佳方法是什么?
即。
西班牙的降雨主要落在飞机上
到
西班牙的雨主要落在飞机上
答案 0 :(得分:21)
所以使用字符串
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)}')
答案 1 :(得分:2)
由于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 Stack Overflow问题。
答案 2 :(得分:1)
很多方式:
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)
更优雅/更复杂 - cell-arrays,textscan和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
答案 3 :(得分:1)
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
不那么优雅,高效,可读性和可维护性。