Question

What's the best way to capitalize / capitalise the first letter of every word in a string in Matlab?

i.e.
the rain in spain falls mainly on the plane
to
The Rain In Spain Falls Mainly On The Plane

Was it helpful?

Solution

So using the string

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

Simply use regexp replacement function in Matlab, regexprep

regexprep(str,'(\<[a-z])','${upper($1)}')

ans =

The Rain In Spain Falls Mainly On The Plain.

The \<[a-z] matches the first character of each word to which you can convert to upper case using ${upper($1)}

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

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

OTHER TIPS

Since Matlab comes with build in Perl, for every complicated string or file processing tasks Perl scripts can be used. So you could maybe 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 Stack Overflow question.

Loads of ways:

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
    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 ellegant and efficient, more readable and maintainable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top