views:

652

answers:

4

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

A: 

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
Nivag
+1  A: 

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.

Marcin
+7  A: 

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)}')
Adrian
+1 Very nice and short.
Marcin
Cheers - although I can't claim too much credit as it's just a slightly tweaked example from the help pages on regular expressions. The string replacement section gives an example for capitalizing the first letter of each sentance in a string.
Adrian
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. :)
Marc
+1  A: 
    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.

Emilio M Bumachar

related questions