更改字符串中指定字符的大小写

时间:2011-09-27 16:36:23

标签: vb.net string localization

我有一个大小写的字符串代表存储在数据库中的邮政地址,但是当缩写与字符串的其余部分分开时,我希望将美国州缩写(例如“ca”到“CA”)大写两边都有空间。

我能做的糟糕方式就是有50个语句,比如

If addressString.Contains(" al ") Then addressString.Replace(" al ", " AL ")
If addressString.Contains(" ak ") Then addressString.Replace(" ak ", " AK ")
...

编辑:这真是一个糟糕的方式!这就是我做的事情:

addressString = StrConv(addressString, VbStrConv.ProperCase)

'无论如何都需要这样做,但它将“ak”变成“Ak”。

Static stateAbbrevs As New List(Of String)(New String() {" Ak ", " Al ", " Ar "...})
    For Each a In stateAbbrevs
        If addressString.Contains(a) Then
            addressString= addressString.Replace(a, a.ToUpper)
        End If
    Next

2 个答案:

答案 0 :(得分:1)

将它们存储在数组中我猜...

Dim States() as string = new string(){" al "," al "}
For i = 0 to States.Length -1
         If addressString.Contains(States(i)) Then addressString = addressString.Replace(States(i), States(i).ToUpper)
Next i

答案 1 :(得分:1)

真正的问题是存储缩写列表的位置。 - 在程序中,在数据库中,在flat或xml文件中。所有这些都很容易变成一个字符串列表,然后遍历该列表,替换目标字符串中的每个出现。

Private states as list(of string) 
Private Function CapitalizeState(ByVal addressText As String) As String
    Dim result as string = addresstext
    For each st as string in states
       result =  Replace( result,  st,   st,   CompareMethod := CompareMethod.Text)
    Next
    Return result
End Function

初始化列表和optimpizations留作练习....