7
A
回答
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
负载:
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高效,更易读和可维护性。
相关问题
- 1. 字符串的首字母大写
- 2. 首字母大写从MySQL与PHP/jQuery拉的每个单词的首字母
- 3. 为字符串中的每个单词首字母大写。本地化问题
- 4. 将列中每个单词的首字母大写Python
- 5. 如何自动大写C#中每个单词的首字母?
- 6. 每个句子的首字母大写
- 7. 大写首字母的姓
- 8. 首字母大写的字符
- 9. 返回每个单词的首字母大写
- 10. SQL:仅首字母大写
- 11. 首字母应大写?
- 12. 大写首字母只
- 13. 首字母大写。 MySQL
- 14. 用大写字母填满句子中的每个单词的首字母大写
- 15. 使用javascript大写首字母大写
- 16. 如何在使用Java的字符串中首字母大写?
- 17. Swift大写字母中每个单词的第一个字母
- 18. 首字母大写除文章,连词和介词外每个单词的首字母
- 19. 在Objective C中的单词中首字母大写?
- 20. 小写的字符串,句首字母大写
- 21. 如何将句首字母的首字母大写?
- 22. 在JavaScript中首字母大写
- 23. 对输入字段中包含的每个单词进行首字母大写
- 24. 特殊字符或字母后首字母大写
- 25. 我需要字符串转换JSP中成首字母大写
- 26. 如何在Perl中使用字符串中的每个单词的首字母大写?
- 27. C#大写首字母的字符串 - 更有效的方法?
- 28. Ektron 9.10 SP1利用显示中的每个单词的首字母大写
- 29. Java字符串首字母缩写
- 30. 大写首字母的每个字,除了网址
是否可以接受其中一个答案,谢谢。 – Morgan 2014-12-08 10:06:35