开发者

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

开发者 https://www.devze.com 2022-12-21 03:50 出处:网络
What\'s the best way to capitalize / capitalise the first lette开发者_运维技巧r of every word in a string in Matlab?

What's the best way to capitalize / capitalise the first lette开发者_运维技巧r 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


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.


Loads of ways:

str = 'the rain in Spain falls mainly on the plane'

spaceInd = strfind(str, ' '); % assume a word is preceded by a space
startWordInd = spaceInd+1;  % words start 1 char after a space
startWordInd = [1, startWordInd]; % manually add the first word
capsStr = upper(str);

newStr = str;
newStr(startWordInd) = capsStr(startWordInd)

More elegant/complex -- cell-arrays, textscan and cellfun are very useful for this kind of thing:

str = 'the rain in Spain falls mainly on the plane'

function newStr = capitals(str)

    words = textscan(str,'%s','delimiter',' '); % assume a word is preceded by a space
    words = words{1};

    newWords = cellfun(@my_fun_that_capitalizes, words, 'UniformOutput', false);
    newStr = [newWords{:}];

        function wOut = my_fun_that_capitalizes(wIn)
            wOut = [wIn ' ']; % add the space back that we used to split upon
            if numel(wIn)>1
                wOut(1) = upper(wIn(1));
            end
        end
end


    str='the rain in spain falls mainly on the plain.' ;
for i=1:length(str)
    if str(i)>='a' && str(i)<='z'
        if i==1 || str(i-1)==' '
            str(i)=char(str(i)-32); % 32 is the ascii distance between uppercase letters and its lowercase equivalents
        end
    end
end

Less ellegant and efficient, more readable and maintainable.

0

精彩评论

暂无评论...
验证码 换一张
取 消