Remove "#" from String - vb.net

Have an email, want to remove the first "#" symbol from it, to then make sure it doesn't have more then one in the second check. Here is currently how I'm doing it.
Dim tempEmail As String = ContactEmail
Dim count As Integer = 0
If tempEmail.IndexOf("#") <> -1 Then 'check for one
count += 1
tempEmail.Remove(tempEmail.IndexOf("#"), 1)
End If
If tempEmail.IndexOf("#") <> -1 Then 'check for two
count += 1
End If
If count = 1 Then
JustifyString(ContactEmail, 66, " ", LEFT_JUSTIFY)
Else
ContactEmail = BLANK_EMAIL
End If
But after debugging, I have found that it never actually removes the "#" symbol from the string from tempEmail. Why?

String is immutable. All String methods do not alter the String, but instead they create a new one and return it. Try this instead:
tempEmail = tempEmail.Remove(tempEmail.IndexOf("#"), 1)

Remove() returns a new string. It does not modify the original.
tempEmail = tempEmail.Remove(tempEmail.IndexOf("#"), 1)

As others have stated, strings are immutable in .NET. The Remove method returns a new string rather than changing the original object. Therefore you need to use:
tempEmail = tempEmail.Remove(tempEmail.IndexOf("#"), 1)
One quick way to determine whether the string contains multiple "#" symbols is via LINQ, rather than using IndexOf multiple times:
Dim input = "foo#bar.com"
Dim count = input.Count(Function(c) c = "#"c)
Console.WriteLine(count)
Then just check If count = 1 just as you do in your original If/Else block.

tempEmail.Remove(tempEmail.IndexOf("#"), 1)
This line creates a new string without the "#". You need to set tempEmail to be equal to the command:
tempEmail = tempEmail.Remove(tempEmail.IndexOf("#"), 1)

Strings are immutable. They don't change. To get the effect you want, change the line that reads:
tempEmail.Remove(tempEmail.IndexOf("#"), 1)
...to:
tempEmail = tempEmail.Remove(tempEmail.IndexOf("#"), 1)

Related

Cut String inside Quotation Mark

I have this String:
"[" & vbCrLf & " ""APPLE""" & vbCrLf & "]"
The only thing I need is APPLE.
I tried a few options with Split, Trim, Left and more, but they didn't work very well.
Thank you very much!
As the comments above have said, there's not enough information to give an answer without making assumptions, which could be wrong. I've assumed you want to extract the value between two quotation marks, regardless of what else is before or after.
If that's what you want, try this:
Dim Result As String = Nothing
Dim source As String = $"[{vbCrLf}""Apple""{vbCrLf}]"
Dim FirstQuote As Integer = source.IndexOf("""")
If FirstQuote > -1 And source.Length > FirstQuote Then
Dim SecondQuote As Integer = source.IndexOf("""", FirstQuote + 1)
If SecondQuote > FirstQuote Then
Result = source.Substring(FirstQuote + 1, SecondQuote - FirstQuote - 1)
End If
End If
If Result Is Nothing Then
'Handle Invalid Format
Else
'Process Result
End If
You would need to modify that so that you passed your source string, rather than defining it in the code. If you wanted to extract multiple words from a single string in the same format, just set FirstQuote = SecondQuote + 1, check that doesn't exceed the length of the source string and loop through again.
I am going to assume that you probably just need to get the first occurance of a string (in this case "apple") within square-brackets using split and so:
Dim AppleString As String = "This is an [Apple] or etc [...]"
console.WriteLine(AppleString.split("[")(1).split("]")(0).trim())
⚠️ This is not a solution for all purposes !!!

How to increase numeric value present in a string

I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub

Find a string between 1 or 2 sets of parenthesis

I'm looking for a way in VB to find a string between two characters,
"(" and ")".
For example, for the string...
"THIS IS (ONE) AND THIS IS (TWO)"
....I would like for a variable to store the characters between the
second set of parenthesis, e.g.
strMyString = "TWO".
But if the string to search only contains one set of parenthesis, to
store this instead. e.g.
strFirstString = "THIS IS (ONE)"
strMyString = "ONE"
As a preliminary answer, you can use this function to find the string within the last pair or brackets in your test string. If the brackets are in the wrong order or if brackets are missing it will throw an exception.
Private Function StringInLastBracketPair(testString As String) As String
Dim startBracket, endBracket As Integer
startBracket = testString.LastIndexOf("(") + 1
endBracket = testString.LastIndexOf(")")
If startBracket >= endBracket Or startBracket = 0 Or endBracket = -1 Then
Throw New System.Exception("String is not formatted properly : " & testString)
End If
StringInLastBracketPair = stringToTest.Substring(startBracket, endBracket - startBracket)
End Function

How to delete a string from a RichTextBox?

I am trying to parse junk and narrow down a bunch of text. How do I delete the current line if a does not match? I would like to remove the line entirely:
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
Dim a As String = RichTextBox1.Lines(i).ToString
If Not a = "SaveThisLine" Then
'delete the active line
End If
Next
Also how would I match partially? Such as if not a = "SaveThisLine" & * (to use a wildcard).
I would not touch original text and rather save valid lines into a StringBuilder, so if line is valid, AppendLine to it. In the end dump back into RichTextBox1.Text using StringBuilder.ToString.
For partial match in VB.NET you can use a native Like operator:
"aaa" Like "a*"
Returns True.
Or use regular expressions:
System.Text.RegularExpressions.Regex.Match("aaa", "^a").Success
Also returns True.
You can do it in this way to:
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
If RichTextBox1.Lines(i) = "2" Then
RichTextBox1.Text = Replace(RichTextBox1.Text, RichTextBox1.Lines(i), "", , 1)
End If
Next

How to split string in group in vb.net

i'm amol kadam,I want to know how to split string in two part.My string is in Time format (12:12).& I want to seperate this in hour & minute format.the datatype for all variables are string. for hour variable used strTimeHr & for minute strTimeMin .I tried below code but their was a exception "Index and length must refer to a location within the string.
Parameter name: length"
If Not (objDS.Tables(0).Rows(0)("TimeOfAccident") Is Nothing Or objDS.Tables(0).Rows(0)("TimeOfAccident") Is System.DBNull.Value) Then
strTime = objDS.Tables(0).Rows(0)("TimeOfAccident") 'strTime taking value 12:12
index = strTime.IndexOf(":") 'index taking value 2
lastIndex = strTime.Length 'Lastindex taking value 5
strTimeHr = strTime.Substring(0, index) 'strTime taking value 12 correctly
strTimeMin = strTime.Substring(index + 1, lastIndex) 'BUT HERE IS PROBLEM OCCURE strTimeMin Doesn't taking any value
Me.NumUpDwHr.Text = strTimeHr
Me.NumUpDwMin.Text = strTimeMin
End If
The simplest way (assumming that you can ensure the format) is to use a split:
dim strTime as string = objDs.Tables(0).Rows(0).("TimeOfAccident")
dim timeParts() as string = split(strTime,":")
dim strTimeHr as string = timeParts(0)
dim strTimeMn as string = timePartS(1)
you'll also want some error handling to check for formatting and that the split generates the array with at least two elements and what not.
EDIT: After looking more closely at your code, I see the cause of your error.
You have this code:
lastIndex = strTime.Length
strTimeHr = strTime.Substring(0, index)
strTimeMin = strTime.Substring(index + 1, lastIndex)
With that last line giving the error.
The reason that you're getting that error is that strings (and other arrays) in VB.Net are ZERO BASED. Which is why in the strTimeHr field, you're starting at position 0. Length gives you the count, which since the array is zero-based, means the count will be one more than available indexes.
I.e. the last element in a zero based array is the length of the array minus 1.
Therefore, changing your original code to this:
lastIndex = strTime.Length - 1
strTimeHr = strTime.Substring(0, index)
strTimeMin = strTime.Substring(index + 1, lastIndex)
will work as well.
string s = "12:13";
DateTime dt = DateTime.Parse(s);
Console.Write(dt.Hour + " " + dt.Minute);
Try something like (String.Split Method )
Dim str As String = "12:13"
Dim strHr = str.Split(":")(0)
Dim strMin = str.Split(":")(1)
Is the datatype of the column "TimeOfAccident" a DateTime? If so, then the simplest solution would be something like:
'Using LINQ to convert the value to a nullable datetime.
Dim timeOfAccident As Nullable(Of DateTime) = dt.Rows(0).Field(Of Nullable(Of DateTime))("TimeOfAccident")
If timeOfAccident.HasValue Then
Me.NumUpDwHr.Text = timeOfAccident.Hour
Me.NumUpDwMin.Text = timeOfAccident.Minute
End If
If the column "TimeOfAccident" is a string, then you can do something like:
Dim timeOfAccidentString As String = dt.Rows(0).Field(String)("TimeOfAccident")
If Not String.IsNullOrEmpty(timeOfAccidentString) Then
Dim accidentTime As DateTime = DateTime.Parse(timeOfAccidentString)
Me.NumUpDwHr.Text = timeOfAccident.Hour
Me.NumUpDwMin.Text = timeOfAccident.Minute
End If