Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 554
Anthony Avatar asked Feb 23 '10 11:02

Anthony


People also ask

How do you capitalize the first letter of each word in MATLAB?

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.

How do you capitalize the first letter of each word in a string?

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.

How do you capitalize certain letters in a string in MATLAB?

Description. newStr = upper( str ) converts all lowercase characters in str to the corresponding uppercase characters and leaves all other characters unchanged.

How do you capitalize every word in a string?

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.


2 Answers

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)}')
like image 104
Adrian Avatar answered Oct 16 '22 15:10

Adrian


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.

like image 35
Marcin Avatar answered Oct 16 '22 15:10

Marcin