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

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"))

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

How to check if one string contains another case insensitively?

comp = StringComparison.OrdinalIgnoreCase
Console.WriteLine(" {0:G}: {1}", comp, s.Contains(sub1, comp))
That seems like the way. However, I tried and it doesn't work. It seems that the only altenative of s.Contains take char() as first argument. If I want to insert string as first argument then I cannot have second argument as StringComparison.OrdinalIgnoreCase.
I got the snippet from https://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx
You can use IndexOf function.
Console.WriteLine(s.IndexOf(sub1, 0, StringComparison. OrdinalIgnoreCase) > -1)
Above snippet prints true or false depending on whether s contains sub1.
Alternatively, if you want to use contains, you can use ToUpper or ToLower as shown below...
Console.WriteLine(" {0:G}: {1}", comp, s.ToUpper().Contains(sub1.ToUpper()))
The link you gave in question shows you how to create a custom extension to string. He also gave the code you have to use to create that custom extension and that method uses IndexOf internally if you had observed.
Source
Try this:
s.ToLowerInvariant().Contains(sub1.ToLowerInvariant())
The link you pointed to in your question defines the follow extension method:
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Function Contains(str As String, substring As String,
comp As StringComparison) As Boolean
If substring Is Nothing Then
Throw New ArgumentNullException("substring",
"substring cannot be null.")
Else If Not [Enum].IsDefined(GetType(StringComparison), comp)
Throw New ArgumentException("comp is not a member of StringComparison",
"comp")
End If
Return str.IndexOf(substring, comp) >= 0
End Function
End Module
Unless you implement this your call to s.Contains(sub1, comp) won't work.

Checking is StringBuilder() AppendLine() is an empty string

I want to conditionally append a string, derived from a function, to a string builder. The required condition is that the function is not returning a blank string ("").
The purpose of conditionally appending the string is to avoid AppendLine() appending a line when the string (returned from the function) being appended is empty.
My current code (wrapping the function in a condition calling the very same function):
Dim builder As New System.Text.StringBuilder()
builder.Append("Some text...").AppendLine()
If Not IsNothing(someFunction(someParameterAA, someParameterAB)) Then
builder.Append(someFunction(someParameterAA, someParameterAB)).AppendLine()
End If
If Not IsNothing(someFunction(someParameterBA, someParameterBB)) Then
builder.Append(someFunction(someParameterBA, someParameterBB)).AppendLine()
End If
builder.AppendLine().Append("...some text.")
Dim s As String = builder.ToString
MessageBox.Show(s)
It is my hope that a more efficient alternative exists (efficient in terms of the amount of code to be written). Ultimately, I'd like to avoid calling the same function twice however I cannot independently add the builder.Append line of code to my function. Is it instead possible to target builder.Append?
Example of the potential logic:
If `builder.Append()` inside the following brackets is not an empty string then:
(
builder.Append(someFunction(someParameterAA, someParameterAB)).AppendLine()
)
If anyone has a solution on the above, bear in mind the prequisite of concision (=< 2) lines of code additional to the builder.Append() line.
I'm open to any other suggestions.
Create another method to do the appending like so:
CheckBeforeAppend(someFunction(someParameterAA, someParameterAB), builder)
CheckBeforeAppend(someFunction(someParameterBA, someParameterBB), builder)
....
Public Sub CheckBeforeAppend(s As String, sb As StringBuilder)
If Not String.IsNullOrEmpty(s)
sb.Append(s).AppendLine()
End If
End Sub
A simple refactor such as this shortens your original code and means you don't need to duplicate the null or empty check on the return value of your function.
And for the extension method (place this code in a Module):
<Extension()>
Public Sub CheckBeforeAppend(s As String, sb As StringBuilder)
If Not String.IsNullOrEmpty(s)
sb.Append(s).AppendLine()
End If
End Sub
usage:
someFunction(someParameterAA, someParameterAB).CheckBeforeAppend(sb)
or for an extension on StringBuilder:
<Extension()>
Public Sub CheckBeforeAppend(sb As StringBuilder, s As String)
If Not String.IsNullOrEmpty(s)
sb.Append(s).AppendLine()
End If
End Sub
usage:
builder.CheckBeforeAppend(someFunction(someParameterAA, someParameterAB))
You can avoid calling the function twice by storing the result of the function in a variable.
Dim myString As String = someFunction(someParameterAA, someParameterAB)
If myString <> "" Then
builder.Append(myString).AppendLine()
End If
myString = someFunction(someParameterBA, someParameterBB)
If myString <> "" Then
builder.Append(myString).AppendLine()
End If
This way you just call the function once and check your conditions with the variable. Also the code looks a lot smaller and more understandable.

Converting characters from Lower to upper case and vice versa 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? :-)

VB.NET If-Else in List

I just want to know if there's an approach in VB.NET that can find if a specific value exist on a list or something which can use in my If-else condition. What I'm doing now is to use this:
If ToStatus = "1CE" Or ToStatus = "2TL" Or ToStatus = "2PM" Then
'Do something
Else
'Do something
End If
This works fine, but how if I have hundreds of string to compare to ToStatus in the future? It will be a nightmare! Now, if such functionality exists, how can I add "And" and "Or" in the statement?
Thanks in advance!
You can use the Contains function:
Dim someList = New List(Of String) From { ... }
If Not someList.Contains(ToStatus) Then
You can do the following:
If {"1CE","2TL","2PM"}.Contains(ToStatus) Then
' ...
End If
Like Slaks pointed out, you can use Contains on an enumerable collection. But I think readability suffers. I don't care if some list contains my variable; I want to know if my variable is in some list.
You can wrap contains in an extension method like so:
Imports System.Runtime.CompilerServices
Module ExtensionMethods
<Extension()> _
Public Function [In](Of T)(ByVal item As T, ByVal ParamArray range() As T) As Boolean
Return range.Cast(Of T).Contains(item)
End Function
End Module
Then call like this:
If ToStatus.In("1CE","2TL","2PM") Then
you may use select case
select case A
case 5,6,7,8
msgbox "you are in"
case else
msgbox "you are excluded"
end select
For .NET 2.0
I came across another problem where SLaks solution won't work, that is if you use .NET 2.0 where method Contains is not present. So here's the solution:
If (Array.IndexOf(New String() {"1CE", "2TL", "2PM"}), ToStatus > -1) Then
'Do something if ToStatus is equal to any of the strings
Else
'Do something if ToStatus is not equal to any of the strings
End If
VB.NET - Alternative to Array.Contains?
Remove duplicates from the list
Dim ListWithoutDuplicates As New List(Of String)
For Each item As String In ListWithDuplicates
If ListWithoutDuplicates.Contains(item) Then
' string already in a list - do nothing
Else
ListWithoutDuplicates.Add(item)
End If
Next