Replace or Remove a character from a string [duplicate] - vb.net

I wrote up some code. The code is shown below. The first part is to read a html into string format. The second part is to search a mark in the string and replace the string by other string.
The 1st part (I test it many times, it works fine)
Public Function ReadTextFile(ByVal TextFileName As String) As String
Dim TempString As String
Dim StreamToDisplay As StreamReader
StreamToDisplay = New StreamReader(TextFileName)
TempString = StreamToDisplay.ReadToEnd
StreamToDisplay.Close()
Return TempString
End Function
The 2nd part (I test it many times, the search and replace does not work. I checked many times that the "TempText" DOES contain string. The "the_key_string" DOES inside the "TempText" String. I check it by using QuickWatch in VB.net. However, the replace function does NOT do its job)
Dim TextPath = C:xxxxxx
TempText = ReadTextFile(TextPath)
TempText.Replace("the_key_string", "replace_by_this_string")
Please help. I have no clue where I made the mistake

String.Replace returns new string instead of modifying the source one. You have to assign it back to your variable:
TempText = TempText.Replace("the_key_string", "replace_by_this_string")
From MSDN:
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Strings are immutable, that means once they are created you cannot modify them. So you have to create a new one and assign that to your string variable:
TempText = TempText.Replace("the_key_string", "replace_by_this_string")
MSDN: String Data Type (Visual Basic):
Once you assign a string to a String variable, that string is
immutable, which means you cannot change its length or contents. When
you alter a string in any way, Visual Basic creates a new string and
abandons the previous one. The String variable then points to the new
string.

You have to assign the value to something, like :
TempText = TempText.Replace("the_key_string", "replace_by_this_string")

This is performing the string replace, but it's not putting the result of it anywhere:
TempText.Replace("the_key_string", "replace_by_this_string")
You need to assign the result to something:
TempText = TempText.Replace("the_key_string", "replace_by_this_string")

The Replace method returns the modified string.
You need something like this:
Dim TextPath = C:xxxxxx
TempText = ReadTextFile(TextPath)
Dim ModifiedString as String
ModifiedString = TempText.Replace("the_key_string", "replace_by_this_string")

"this is a string"
If you do Replace 'string' with 'whatever' this string should be: "this is a whatever". so what you can do is put that in a new string. how? replace method returns a string so, it is easy :)
see this: msdn

try these and one might work. i think that it is the underscore.
TempText.Replace("thekeystring", "replace_by_this_string")
TempText.Replace("the key string", "replace_by_this_string")
TempText.Replace("the__key__string", "replace_by_this_string")

Related

Vb.net, replace any number at the end of a string with a placeholder

I have many strings that have numbers at the end. The numbers can be of any size, for example:
myvar123
mysecondvar3
mythirdvar219107
The strings can have numbers even inside the name, not only at the end.
for example:
my2varable123
some123variable9480395
I would need to replace any number at the END with a placeholder. (NOT those inside the varname.)
for example:
my2varable123 should become: my2variable%placeholder%
some123variable9480395 should become: some123variable%placeholder%
The only way that comes to my mind is to go through the string using .right() and remove the char if it is numeric until I find the first non numeric char. Then in the end append the placeholder, but it looks like a lot of work for a rather simply problem.
Is there a better way to do this?
You could use a Regex for this.
Dim str As String = "some123variable9480395"
Dim pattern As String = "\d+$"
Dim replacement As String = "%placeholder%"
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(str, replacement)

visual studio split function issue

I try to call split function on visual studio as below and i expect it return me 2 item in array after split, but vb return 5 results from my coding. It is consider vb issue or my coding issue?
Whole string is "NAME":"ALICE"
Dim a As String = """NAME"":""ALICE"""
Dim b() As String = a.Split(""":")
Output I expected in array after split
(1) "NAME
(2) "ALICE"
You were using this overload of String.Split(Char[]). Note that takes an array of characters. String is convertible to an array of characters (and that's why you could compile) but it is not equal. Try putting Option Strict On at the top of your code. It won't compile as you have it anymore :)
When passing a single string, each character in the string is used to split. Including each " in your argument, ":. It will split on " and :. You can get around it by passing a string array to Split using this overload of String.Split(String[], SplitStringOptions). Pass a single element array like this
Dim b = a.Split({""":"}, StringSplitOptions.RemoveEmptyEntries)
Yes, that is exactly as you said,
"NAME
"ALICE"
Do you want to get rid of the quotes in the result? You can do this
Dim b = a.Split({":", """"}, StringSplitOptions.RemoveEmptyEntries)
Then it's this,
NAME
ALICE
Dim a As String = """NAME"":""ALICE"""
Dim b() As String = a.Split(":")
this is how it evaluates

Remove the character alone from the string

My code retrieves the data from various resources .
And output will be like below
UNY4/4/2010
hds04/5/2010
saths04/22/2013
But I want the output like this
4/4/2010
4/5/2010
04/22/2013
Is there any way to do this ?
You need to use a regular expression that finds all uppercase and lowercase characters and replaces them with a blank, like this:
Dim rgx As New Regex("[a-zA-Z]")
str = rgx.Replace(str, String.Empty)
An alternate solution is to look for the first numeric digit, then discard all text before that.
Function GetDate(data As String) As Date
Dim indexFirstNum As Integer = data.IndexOfAny("0123456789".ToCharArray())
Dim datePortion As String = data.Substring(indexFirstNum)
Return Date.Parse(datePortion)
End Function

splitting a string in VB

I have a ComboBox which I assign to a variable:
Dim var as String = ComboBox1.SelectedValue
Dim name As String = var.Split(",")
This gives me the error
Value of type '1-dimensional array of string' cannot be converted to String
Any ideas as to where I'm going wrong?
Split returns an array of strings. Your variable needs to be changed to an array, not just a single string.
My VB is a bit rusty, but I think you have to make name an array:
Dim name() As String = var.Split(",")
name needs to be declared as an array.
dim name() as string = var.split(",")
The split() method will break up the string based on the given character and put each newly created string into an array and return it.
This is what your error message is telling you:
Value of type '1-dimensional array of string' cannot be converted to String
The method returns an array of string, but your trying to put it into just a string!
EDIT: In response to your answer...
So far you've managed to split the string yourself with the split method. To output this to your message box, you need to concatenate the two elements in the proper order:
msgbox(name(1) & " " & name(0))
Notice I indexed the array twice! Element 1 is the first name, element 0 is the last name. Remember you got this name in lname,fname format. Passing the array itself doesn't make sense! Remember, a datatype is not equal to an array of that type, they are two different things. Therefore a string is not compatible with a string array. However, each individual element of the array is a string, and so each of those are compatible with the string type (because they're the same thing)!
Dim var As String = ComboBox1.SelectedValue
Dim temp() As String = Split(var, ",", -1, CompareMethod.Binary)
Dim name As String = temp(0)
Or maybe "name" isn't an array and the goal is to populate "name" with everything up until the first comma, in which case the fix would be:
Dim name as String = var.Split(",")(0)
Note: assumes that var is not Nothing.

How to split in VB.NET

I am using VB.NET code.
I have got the below string.
http://localhost:3282/ISS/Training/SearchTrainerData.aspx
Now I want to split the above string with "/" as well. I want to store the value SearchTrainerData.aspx in a variable.
In my case
Dim str as String
str = "SearchTrainerData.aspx"
What would be the code which will split the above string and further store it in a variable?
Try to use the function String.Split.
Your "string" is obviously a URL which means you should use the System.Uri class.
Dim url As Uri = New Uri("http://localhost:3282/ISS/Training/SearchTrainerData.aspx")
Dim segments As String() = url.Segments
Dim str As String = segments(segments.Length - 1)
This will also allow you to get all kinds of other interesting information about your "string" without resorting to manual (and error-prone) parsing.
The Split function takes characters, which VB.NET represents by appending a 'c' to the end of a one-character string:
Dim sentence = "http://localhost:3282/ISS/Training/SearchTrainerData.aspx"
Dim words = sentence.Split("/"c)
Dim lastWord = words(words.length - 1)
I guess what you are actually looking for is the System.Uri Class. Which makes all string splitting that you are looking for obsolete.
MSDN Documentation for System.Uri
Uri url = new Uri ("http://...");
String[] parts = url.Segments;
Use split(). You call it on the string instance, passing in a char array of the delimiters, and it returns to you an array of strings. Grab the last element to get your "SearchTrainerData.aspx."