Character conversion from lower to upper case and vice versa VB.Net

had a search around and cannot find the answer.

I am tasked with transforming the capitalization of strings from what it is, whether in lower case or in upper case, and swap them around.

Example: - Input: - "HeLlO" and output: - "hElLo"

I understand that I need to use a for loop, but I could not figure out how to go through each character, check the case and switch it if necessary.

I can make a for loop that counts and displays single characters or a simple If statement to convert the entire string to top or bottom, but if I try to combine 2, my logic does not work correctly.

Can anyone help at all?

+4
source share
2 answers

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
+4
source

As a Linq request:

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's writing loops these days ?:-)

+3
source

Source: https://habr.com/ru/post/1523531/


All Articles