Search code examples
stringmatlabcapitalize

Capitalize / Capitalise first letter of every word in a string in Matlab?


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


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)}')