Here is one easy way to do this:
Public Function InvertCase(input As String) As String
Dim output As New StringBuilder()
For Each i As Char In input
If Char.IsLower(i) Then
output.Append(Char.ToUpper(i))
ElseIf Char.IsUpper(i) Then
output.Append(Char.ToLower(i))
Else
output.Append(i)
End If
Next
Return output.ToString()
End Function
It simply looks at each character in the source line, checks in which case it corrects it, and then adds this fixed character to a new line (through the object StringBuilder).
As Neolisk suggests in the comments below, you can make it cleaner by creating another method that converts one character, for example:
Public Function InvertCase(input As Char) As Char
If Char.IsLower(input) Then Return Char.ToUpper(input)
If Char.IsUpper(input) Then Return Char.ToLower(input)
Return input
End Function
Public Function InvertCase(input As String) As String
Dim output As New StringBuilder()
For Each i As Char In input
output.Append(InvertCase(i))
Next
Return output.ToString()
End Function
Using the same function for InvertCase(Char), you can also use LINQ, for example:
Public Function InvertCase(input As String) As String
Return New String(input.Select(Function(i) InvertCase(i)).ToArray())
End Function
source
share