Search code examples
matlabfindstrcapitalizationcamelcasingcapitalize

Capitalizing letters following a space in MATLAB, then removing the space


o I am a neuroscience/biomedical engineering major currently taking a class in programming MATLAB. I have a hw program I have run into a problem with. I am super close to figuring it out. Basically I have to take a phrase like "woot I love matlab' and get out 'wtILvMtlb'. I've removed the spaces, and I've removed the vowels, but I can't seem to get it to capitalize the letters after the spaces. When I try, the second I take out the spaces, it goes a little crazy. I technically haven't learned the regexprep function either, but since I found it I figured I might as well use it. The teacher doesn't care. She probably wants us to do some indexing stuff to get our result, but if the regexprep works, I'll take that.

function[cameltoe] = abbreviatingCamelCase(firstWord)

indexing = find(firstWord(1:end - 1) == ' ');%I want to find all the spaces here
firstWord( indexing + 1) = upper(firstWord(indexing + 1)); %I want to uppercase all the words   following a space
firstWord(firstWord == ' ') = [];
firstWord(ismember(firstWord, ' aeiou')) = [];
cameltoe = firstWord;

I need to convert 'one fish two fish three fish' into 'onFshTwFsh'. I'm close, but not quite there. This is my final issue. My code takes out the first o. Indexing doesn't seem to be working. I've tried to index it like six different ways.


Solution

  • You can do this with a couple of calls to REGEXPREP.

    >> str = 'i love matlab'
    str =
    i love matlab
    >> cap = regexprep(str, '(?<=(^| ))(.)', '${upper($1)}')
    cap =
    I Love Matlab
    >> result = regexprep(cap, '[aeiou ]', '')
    result =
    ILvMtlb
    

    The first REGEXPREP uses a "lookahead" operator to find spaces or the beginning of the string, and then picks the next character and replaces it with the upper-case version.

    The second REGEXPREP simply uses a character group to replace vowels and spaces with nothing. Depending on whether you want to remove capitalised vowels too, you might need to use [aeiouAEIOU ] as the character group.