Capitalization / Capital Letter of Each Word in a String in Matlab?

What is the best way to use / capitalization of the first letter of each word in a string in Matlab?

those.
rain in Spain falls mainly on a plane
image rain in Spain falls mainly on the planet

+7
string capitalize matlab
source share
4 answers

So using the line

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

Just use the regexp replacement function in Matlab, regexprep

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

\<[az] matches the first character of each word to which you can convert to uppercase using ${upper($1)}

This will also work using \<\w to match the character at the beginning of each word.

 regexprep(str,'(\<\w)','${upper($1)}') 
+21
source share

Since Matlab comes with build in Perl , Perl scripts can be used for every complex string or file processing task. So you can use something like this:

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

where capitalize.pl is a Perl script as follows:

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

The perl code was taken from this question.

+2
source share

Load methods:

 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) 

More elegant / complex - cell arrays, textscan and cellfun are very useful for this kind of thing:

 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 
+1
source share
  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 

Less flexible and effective, readable and supported.

+1
source share

All Articles