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
MATLAB provides the following functions to convert between lower and upper case letters: lower(str) converts all upper case letters in the string str to lower case. upper(str) converts all lower case letters in the string str to upper case.
To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it.
Description. newStr = upper( str ) converts all lowercase characters in str to the corresponding uppercase characters and leaves all other characters unchanged.
We can capitalize each word of a string by the help of split() and substring() methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or charAt() method. Let's see the example to capitalize each word in a string.
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)}')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With