8

Matlabで文字列内のすべての単語の最初の文字を大文字にする/大文字にする最良の方法は何ですか?

つまり、スペインの雨は主に飛行機 に
降り、スペインの雨は主に飛行機に降ります

4

4 に答える 4

23

したがって、文字列を使用します

str='the rain in spain falls mainly on the plain.'

Matlabのregexp置換関数、regexprepを使用するだけです

regexprep(str,'(\<[a-z])','${upper($1)}')

ans =

The Rain In Spain Falls Mainly On The Plain.

\<[a-z]、を使用して大文字に変換できる各単語の最初の文字と一致します${upper($1)}

これは\<\w、各単語の先頭の文字と一致させるために使用することでも機能します。

regexprep(str,'(\<\w)','${upper($1)}')
于 2010-02-23T14:58:37.667 に答える
2

MatlabにはPerlが組み込まれているため、複雑な文字列またはファイル処理タスクごとにPerlスクリプトを使用できます。したがって、次のようなものを使用できます。

[result, status] = perl('capitalize.pl','the rain in Spain falls mainly on the plane')

ここで、capitalize.plは次のようなPerlスクリプトです。

$input  = $ARGV[0];
$input =~ s/([\w']+)/\u\L$1/g;
print $input;

Perlコードは、このStackOverflowの質問から取得されました。

于 2010-02-23T14:51:48.113 に答える
1

たくさんの方法:

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)

よりエレガント/複雑-cell-arrays、textscan、cellfunは、この種のものに非常に役立ちます。

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
于 2010-02-23T13:14:55.327 に答える
1
    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

エレガントで効率が低く、読みやすく、保守しやすい。

于 2010-02-23T15:59:47.470 に答える