在Matlab中如何将字符串中的每个单词的首字母大写?

8
什么是在Matlab中将字符串中每个单词的首字母大写的最佳方法?
例如: the rain in spain falls mainly on the plane 转换为: The Rain In Spain Falls Mainly On The Plane

1
能否接受其中一个答案,谢谢。 - Morgan
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)}')

1
谢谢 - 尽管我不能太自豪,因为这只是在正则表达式帮助页面上稍作修改的示例。字符串替换部分提供了一个示例,用于将字符串中每个句子的第一个字母大写。 - Adrian
3
当一些人面临问题时,他们会想:“我知道,我会使用正则表达式。”现在他们有了两个问题。 :) - Marc

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 的 this 问题。

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

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

更易读和可维护,不那么优雅和高效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接