2010-02-23 2076 views

回答

21

因此,使用字符串

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来匹配每个单词开头的字符。

+1

+1非常好,很短。 – Marcin 2010-02-23 15:17:29

+1

干杯 - 虽然我不能声称太多的功劳,因为它只是来自正则表达式上帮助页面的稍微调整的示例。字符串替换部分给出了一个例子,用于在字符串中大写每个惯例的第一个字母。 – Adrian 2010-02-23 15:27:56

+3

有些人遇到问题时,会想:“我知道,我会用正则表达式。”现在他们有两个问题。 :) – Marc 2010-02-23 17:53:32

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 
2

由于Matlab自带的build in 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代码从this堆栈溢出问题被采取。

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 

少ellegant高效,更易读和可维护性。