将字母串中的三个字母单词的第一个和最后一个字母大写

时间:2016-09-20 23:44:38

标签: matlab

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

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行代码是什么,然后其他人试图得到它以便找到第一个和最后一个字母的位置,然后将它们大写?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

正则表达式绝对是最佳选择。我将建议稍微不同的路线,即使用tokenExtents的{​​{1}}标志返回索引:

regexpi

使用文件交换中的matlab ipusum函数,我生成了1000段随机文本字符串,其平均字长为4 +/- 2。

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{:}]));

结果是一个177,575个字符串,包含5,531个3个字母的单词。我使用str = lower(matlab_ipsum('WordLength', 4, 'Paragraphs', 1000)); 来检查timeitregexprepregexpi的执行时间。使用tokenExtents的速度要快一个数量级:

regexpi