2010-02-23 234 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高效,更易讀和可維護性。