2016-09-20 135 views
0

我想大写字母中只有三个字母单词的第一个和最后一个字母。到目前为止,我已经尝试大写字母中的三个字母单词的第一个和最后一个字母

spaces = strfind(str, ' '); 
spaces = [0 spaces]; 
lw = diff(spaces); 
lw3 = find(lw ==4); 
a3 = lw-1; 
b3 = spaces(a3+1); 
b4 = b3 + 2 ; 
str(b3) = upper(str(b3)); 
str(b4) = upper(str(b4); 

我们必须找到其中的3个字母的单词是第一所以这就是第4行代码,然后其他人都试图得到它,这样它会发现哪里第一个和最后一个字母是,然后大写他们?

+0

什么问题? – excaza

+0

'str'中每个单词的第一个字母的大写位置是不是'spaces(lw3)+ 1'? – beaker

+2

我建议[橡皮鸭调试](https://en.wikipedia.org/wiki/Rubber_duck_debugging),而不是混淆你自己的变量名称。你不会从短变量名获得任何东西,而是使用有意义的东西。 – excaza

回答

5

我会使用正则表达式来识别3个字母的单词,然后使用regexprep结合一个匿名函数来执行案例转换。

str = 'abcd efg hijk lmn'; 

% Custom function to capitalize the first and last letter of a word 
f = @(x)[upper(x(1)), x(2:end-1), upper(x(end))]; 

% This will match 3-letter words and apply function f to them 
out = regexprep(str, '\<\w{3}\>', '${f($0)}') 

% abcd EfG hijk LmN 
0

正则表达式肯定是要走的路。我要提出一个稍有不同的路线,那就是返回使用tokenExtents标志指数regexpi

str = 'abcd efg hijk lmn'; 

% Tokenize the words and return the first and last index of each 
idx = regexpi(str, '(\<w{3}\>)', 'tokenExtents'); 

% Convert those indices to upper case 
str([idx{:}]) = upper(str([idx{:}])); 

从文件交换使用matlab ipusum功能,我产生了1000款随机文本串,平均字长4 +/- 2.

str = lower(matlab_ipsum('WordLength', 4, 'Paragraphs', 1000)); 

结果是177,575个字符串,包含5,531个3个字母的单词。我使用timeit来检查使用regexprepregexpitokenExtents的执行时间。使用regexpi的速度要快一个数量级:

regexpi = 0.013979s 
regexprep = 0.14401s 
相关问题