Capitalizing every word in a string
6 views (last 30 days)
Show older comments
str='The bottom of the deep blue sea'
strN='The Bottom Of The Deep Blue Sea'
To convert the string 'str' to 'strN' is used:
regexprep(str,'(\<[a-z])','${upper($1)}')
Can someone please xeplain this? Another suggestion which did not work was:
regexprep(str,'(\<\w)','${upper($1)}')
Is there a simpler (it is ok if it is longer) way of doing this?
Accepted Answer
Jan
on 17 Jan 2019
Edited: Jan
on 17 Jan 2019
I like simple Matlab code:
m = [false, isspace(str)];
m = m(1:length(str));
str(m) = upper(str(m))
By the way, tested with: '', ' ', 'a', 'aA', ' a', ' a ', ' ab c', ' ab c ' .
Some timings:
str0='The bottom of the deep blue sea';
tic
for k = 1:1e4
str = str0;
m = [false, isspace(str)];
m = m(1:length(str));
str(m) = upper(str(m));
end
toc
tic
for k = 1:1e4
str = str0;
str = regexprep(str,'(\<[a-z])','${upper($1)}');
end
toc
0.17 seconds % Simple Matlab
3.24 seconds % Powerful REGEXP
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!