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

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?

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

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? :-)

Related

VB.net regex exclude certain characters from string

I am using regex.ismatch to check a string doesn't contain any one of a list of characters such as £&+(/?!;:* And also a quotation mark " not sure how to place that...
But can't get to to work...
If Regex.ismatch(Line, "^[^##£&+()*']"). Then
Msgbox("error")
End If
But doesn't work for me?
Any suggestions
You could do this pretty easily without Regex by simply doing something like this:
Public Shared Function HasSpecialChars(ByVal str As String) As Boolean
Const specialChars As String = "!##$%^&*()"
Dim indexOf As Integer = str.IndexOfAny(specialChars.ToCharArray())
Return indexOf <> -1
End Function

Visual Basic .Net Public Function decodes a one line procedure before it gets executed

I encountered an issue with Function and Procedure while experimenting with some code, as below:
Module mod1
Class ExampleApp
Dim textvalue as String = "dGhpcyBpcyBhbiBleGFtcGxlIG9mIGEgdGV4dC4="
Dim string1 as String = "Convert.FromBase64String(input)"
Public Function DecodeB64(ByVal input As String) As String
Return System.Text.Encoding.UTF8.GetString(string1)
End Function
End Class
End Module
The question is, is it possible to encode the statement inside the Public Function before it gets executed?
I have seen some cases where they implemented it on PHP Scripts, where the whole script is encoded before it gets executed. I have tried my best in applying the same concept by storing "Convert.FromBase64String(input)" to a string variable but I'm encountering an issue like this:
Value of type 'String' cannot be converted to '1-Dimensional array of
Byte'
When I don't apply this concept, the text in base64 gets decoded smoothly. My main goal is that I want to obscure the statement or group of statements as much as possible. What seems to be the problem in this Error?
You have 2 mistakes below in the example code:
First, you should know that Convert.FromBase64String() returns
Byte() array, hence you can't assign it to string variable/field.
Second, Encoding.GetString() requires Byte() array as parameter,
but you're passing string to it, hence InvalidCastException occurred.
The correct usage of them should be like this:
Public Function DecodeB64(ByVal input As String) As String
' make sure the input string is Base64 formatted
Dim bytearray As Byte() = Convert.FromBase64String(input)
' decoding from byte array
Return System.Text.Encoding.UTF8.GetString(bytearray)
End Function
' usage
Dim textvalue as String = "dGhpcyBpcyBhbiBleGFtcGxlIG9mIGEgdGV4dC4="
Dim result As String = DecodeB64(textvalue)
Working example: .NET Fiddle demo

Display the first word of input string in UpperCase letters in VB.NET?

How to display the first word of input string in uppercase letters. Display with using message box.
Example:
inputed String = Advance Programing using VB.Net
the function should display = ADVANCE
Dim words = input.Split()
Dim result = String.Format("{0} {1}",
words(0).ToUpper(),
String.Join(" ", words.Skip(1)))
Edit: oh, just the first word, then use words(0).ToUpper
Public Function GetFirstWordUpperCase(ByVal input As String) As String
Return If(String.IsNullOrEmpty(input) Or String.IsNullOrWhiteSpace(input), Nothing, input.Split()(0).ToUpper())
End Function
Checks if the input string is null, empty or whitespace then returns what you wanted if it is not.
For instance, GetFirstWordUpperCase("how are you") returns "HOW"
Simply do MsgBox(GetFirstWordUpperCase("how are you")) to display the result.
Btw instead of returning Nothing, you could throw an error and catch it where you use the function, it's just the basic idea.

VB.Net Extract numbers from string function

My request is one that can extract a number somewhat by a search.
Example:
animalsOwned|4 would return an containing "4"
animals|3|2|1|3 would return an array containing "3", "2", "1", "3"
This would make it easier for me during a file stream reader.
Thank you
Dim astring = "ABCDE|1|2|3|4"
Dim numbers = (From s In astring
Where Char.IsDigit(s)
Select Int32.Parse(s)).ToArray()
This LINQ statement should help. It simply checks each character in a string to see if it's a digit. Note that this only applies to single digit numbers. It becomes a bit more complicated if you want "ABC123" to return 123 vs. 1, 2, 3 array.
Try regular expression. It's a powerful tool for simple text parsing.
Imports System.Text.RegularExpressions
Namespace Demo
Class Program
Shared Function Main(ByVal args As String()) As Integer
Dim array As Integer() = ExtractIntegers("animals|3|2|1|3")
For Each i In array
Console.WriteLine(i)
Next
Return 0
End Function
Shared Function ExtractIntegers(ByVal input As String) As Integer()
Dim pattern As String = "animals(\|(?<number>[0-9]+))*"
Dim match As Match = Regex.Match(input, pattern)
Dim list As New List(Of Integer)
If match.Success Then
For Each capture As Capture In match.Groups("number").Captures
list.Add(Integer.Parse(capture.Value))
Next
End If
Return list.ToArray()
End Function
End Class
End Namespace
I haven't programmed VB for awhile but I'll give you some pseudo code:
First, loop through each line of file. Call this variable Line.
Then, take the index of what you're searching for: like Line.indexOf("animalsOwned")
If it returns -1 it isn't there; continue.
Once you find it, add the Index variable to the length of the search string and 1. (Index=Index+1+Len(searchString))
Then, take a substring starting there, and end at the end of the line.
Explode the substring by | characters, then add each into an array.
Return the array.
Sorry that I can't give you much help, but I'm working on an important PHP website right now ;).
You can do a variable.Split("|") and then assign each piece to an array level.
You can do a count on string and with a while or for loop, you can assign the splited sections to array levels. Then you can do a IsNumeric() check for each array level.

VB.NET string manipulation -- caps to only one letter caps

So I have a string "NEW".
What is the SIMPLEST way to convert that string to "New".
Basically right now I'm doing this:
Case "NEW"
makes = connector.GetMakesByYear(_AuthorizationKey, "NewCar", CDate(Now), Year)
Case "USED"
makes = connector.GetMakesByYear(_AuthorizationKey, "UsedCar", CDate(Now), Year)
And I would prefer not to use a case statement because it's only one parameter that needs to change, and both are appended with "Car".
Using the “old” string functions, you can use this:
result = StrConv("hello world", VbStrConv.ProperCase)
to convert a string to “proper case”. However, in your case this would probably result in (if I read this right) “Usercar”, not “UserCar”.
You may use:
String.Format("{0}{1}", carType.Substring(0, 1).ToUpper(), carType.Substring(1).ToLower())
Regards
If this is something you plan on using often, you might consider creating an extension function for it:
Public Module ObjectExtensions
<System.Runtime.CompilerServices.Extension()>
Public Function firstLetterToUpper(ByVal s As String) As String
Return Char.ToUpper(s.First()) + New String(s.Skip(1).Select(Function(x) Char.ToLower(x)).ToArray())
End Function
End Module
Then you can do something like this:
"USED".firstLetterToUpper()
Which returns "Used"
Obviously you can change the function body with something more efficient like Guilherme's or Konrad's answer, but making an extension function for this can be quite useful if you do plan on doing something like this often, or if you are just a fan of readability.
Here what I have done!
Function InitUpperCase(ByVal str As String) As String
If String.IsNullOrEmpty(str) Then
Return str
End If
Dim charlist() As Char = str.ToCharArray
charlist(0) = Char.ToUpper(charlist(0))
Return New String(charlist)
End Function
to see Output
MessageBox.Show(InitUpperCase("my first letter"))