什么是在Matlab中将字符串中每个单词的首字母大写的最佳方法?
例如: the rain in spain falls mainly on the plane 转换为: The Rain In Spain Falls Mainly On The Plane
例如: the rain in spain falls mainly on the plane 转换为: The Rain In Spain Falls Mainly On The Plane
str='the rain in spain falls mainly on the plain.'
在Matlab中,只需使用正则表达式替换函数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)}')
有很多种方法:
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
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
更易读和可维护,不那么优雅和高效。