8

在Matlab中将字符串中每个单词的首字母大写/大写的最佳方法是什么?


西班牙的雨主要落在飞机上 西班牙的雨主要落在
飞机

4

4 回答 4

23

所以使用字符串

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

只需在Matlab中使用正则表达式替换功能,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 代码取自这个Stack Overflow 问题。

于 2010-02-23T14:51:48.113 回答
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 回答
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)

更优雅/更复杂——单元数组、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 回答