2010-02-23 11 views

risposta

21

Quindi, utilizzando la stringa

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

sufficiente utilizzare la funzione di sostituzione regexp in Matlab, regexprep

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

ans = 

The Rain In Spain Falls Mainly On The Plain. 

Il \<[a-z] corrisponde al primo carattere di ogni parola a cui è possibile convertire in maiuscolo utilizzando ${upper($1)}

Questo funzionerà anche utilizzando \<\w per abbinare il carattere all'inizio di ogni parola.

+1

+1 Molto bello e breve. – Marcin

+1

Cheers - anche se non posso pretendere troppo credito visto che è solo un esempio leggermente ottimizzato dalle pagine di aiuto sulle espressioni regolari. La sezione di sostituzione delle stringhe fornisce un esempio per capitalizzare la prima lettera di ciascuna sentanza in una stringa. – Adrian

+3

Alcune persone, di fronte a un problema, pensano "Lo so, userò le espressioni regolari". Ora hanno due problemi. :) – Marc

1

Carichi di modi:

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) 

Altro elegante/complesso - gli array di celle, textscan e cellfun sono molto utili per questo tipo di cose:

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

Poiché Matlab viene fornito con build in Perl, per ogni complicata attività di elaborazione di stringhe o file possono essere utilizzati script Perl. Così si potrebbe forse usare qualcosa di simile:

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

dove capitalize.pl è uno script Perl come segue:

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

Il codice Perl è stato preso da this Stack Overflow domanda.

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 

Meno Ellegant ed efficiente, più leggibile e mantenibile.

Problemi correlati