读书人

怎么将字符串中英文单词的首字母大写

发布时间: 2012-03-06 20:47:55 作者: rapoo

如何将字符串中英文单词的首字母大写?
我以前是用正则取出每个单词,然后首字母大写,最后把单词全部替换回去,但是这样很麻烦,而且替换时会吧长单词中包含的短单词也替换掉。
大家有什么好的方法?

[解决办法]

C# code
void Main(){    string str="how are you ? i am tim";    str=Regex.Replace(str,"(?<![a-z])([a-z])(?=[a-z]*\\s*)",m=>m.Groups[1].Value.ToUpper());    Console.WriteLine(str);    //How Are You ? I Am Tim}
[解决办法]
呵呵,我换种方式写:
C# code
        string str = "how are you ? i am migaga";        string r = Regex.Replace(str, @"([a-z])([a-z]*)", delegate(Match match) { return match.Groups[1].Value.ToUpper() + match.Groups[2].Value; });        Response.Write(r);
[解决办法]
VB.NET code
dim S as string = "how are you ? i am migaga"dim SP() as string=S.split(" ")dim Sb as new system.text.stringbuilderfor I as integer=0 to sp.length-1sb.append(iif(sp(i).length<>1,sp(i).substring(0,1).toupper & sp(i).substring(1,sp(i).length-2),sp(i).toupper)nextconsole.writeline(sb.tostring)
[解决办法]
Str = Regex.Replace(Str, "(?<!\w)(\w)(?=\w*)", Function(m As Match) m.Groups(1).Value.ToUpper)
[解决办法]
VB.NET code
       Const LETTERS As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"        Dim S As String = "how are you?i am wahaha."        Dim C() As Char = S.ToCharArray        Dim iWord As Integer = 0        Dim bWord As Boolean = True        For iWord = C.GetLowerBound(0) To C.GetUpperBound(0)            If LETTERS.IndexOf(C(iWord)) >= 0 Then                If bWord Then                    C(iWord) = CType(C(iWord).ToString.ToUpper, Char)                    bWord = False                End If            Else                bWord = True            End If        Next        S = C        MsgBox(S)
[解决办法]
VB.NET code
Dim result as string = Regex.Replace(yourStr,"(?<![a-z\-])[a-z](?=[a-z\-]*)", Function(m As Match) m.Value.ToUpper())
[解决办法]
"(?<!'|\w)(\w)(?=\w*)"
[解决办法]
VB.NET code
Dim result as string = Regex.Replace(yourStr,"(?<![a-z\-'])[a-z](?=[a-z\-]*)", Function(m As Match) m.Value.ToUpper()) 

读书人网 >VB Dotnet

热点推荐