只改写首字母而不改变任何数字或标点符号

时间:2014-02-06 05:23:52

标签: matlab

我想修改一个字符串,该字符串将使第一个字母大写,所有其他字母更低,其他任何内容都将保持不变。

我试过了:

    function new_string=switchCase(str1)
%str1 represents the given string containing word or phrase
str1Lower=lower(str1);
spaces=str1Lower==' ';
caps1=[true spaces];
%we want the first letter and the letters after space to be capital.
strNew1=str1Lower;
strNew1(caps1)=strNew1(caps1)-32;
end

如果空格后面只有一个字母,那么这个功能可以很好地工作。如果我们还有其他任何例子:

     str1='WOW ! my ~Code~ Works !!'

然后它给出了      new_string =     “哇我的^代码〜工作!” 但是,它必须给出(根据要求),

    new_string =
    'Wow!  My ~code~ Works !'

我找到了一个与此问题相似的代码。但是,这是模棱两可的。如果我不明白,我可以在这里提问。

任何帮助将不胜感激!感谢。

1 个答案:

答案 0 :(得分:2)

有趣的问题+1。

我认为以下内容应符合您的要求。我把它作为一个示例子程序写下来并分解了每一步,因此很明显我正在做什么。从这里将它压缩成函数应该是直截了当的。

注意,使用单个正则表达式可能还有一种聪明的方法可以做到这一点,但我对正则表达式不是很好:-)我怀疑基于正则表达式的解决方案运行速度比我的速度快得多提供(但很高兴被证明是错误的)。

%# Your example string
Str1 ='WOW ! my ~Code~ Works !!';

%# Convert case to lower
Str1 = lower(Str1);

%# Convert to ascii
Str1 = double(Str1);

%# Find an index of all locations after spaces
I1 = logical([0, (Str1(1:end-1) == 32)]);

%# Eliminate locations that don't contain lower-case characters
I1 = logical(I1 .* ((Str1 >= 97) & (Str1 <= 122)));

%# Check manually if the first location contains a lower-case character
if Str1(1) >= 97 && Str1(1) <= 122; I1(1) = true; end;

%# Adjust all appropriate characters in ascii form
Str1(I1) = Str1(I1) - 32;

%# Convert result back to a string
Str1 = char(Str1);