Converting characters from Lower to upper case and vice versa VB.Net

15,190

Solution 1

Here is one simple way to do it:

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 just loops through each character in the original string, checks to see what case it is, fixes it, and then appends that fixed character to a new string (via a StringBuilder object).

As Neolisk suggested in the comments below, you could make it cleaner by creating another method which converts a single character, like this:

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 that same function for InvertCase(Char), you could also use LINQ, like this:

Public Function InvertCase(input As String) As String
    Return New String(input.Select(Function(i) InvertCase(i)).ToArray())
End Function

Solution 2

As a Linq query:

Dim input = "HeLlO"
Dim output = new String(input.Select(Function(c)
                            Return If(Char.IsLower(c),Char.ToUpper(c),Char.ToLower(c))
                        End Function).ToArray())
Console.WriteLine(output)

Honestly, who writes loops these days? :-)

Share:
15,190
Admin
Author by

Admin

Updated on June 12, 2022

Comments

  • Admin
    Admin almost 2 years

    had a search around and can't find an answer.

    I've been tasked with converting a strings capitalization from whatever it is in Be it lower case or upper case and swap them round..

    For Example :- Input :- "HeLlO" and Output :- "hElLo"

    I understand that i need to use a for loop but have not been able to figure out how to step through each character, check the case and switch it if needs be.

    I can make a for loop that counts through and displays the individual characters or a simple If statement to convert the whole string into Upper or lower but if i try to combine the 2 my logic isn't working right.

    Can anyone help at all?