remove from String in VB - vb.net

I have inserted a option in Dorpdown as follows
<option>إختر </option>
When I select this text from server side on any event I get this value
"إختر       ‎"
Now I want to replace this white space in the string. I have tried replace method of String class. But its not working.
str = str.replace(" ","")
Plz suggest

What you should do first is decode the HTML, such that text like but also & are converted to their textual counterparts (" " and "&"). You can do this with: WebUtility.HtmlDecode. Next you can use String.Trim to remove leading and tailing spaces.
Example:
string s = "إختر ";
string r = WebUtility.HtmlDecode(s).Trim();
Or the VB.NET equivalent:
Dim s As String = "إختر "
Dim r As String = WebUtility.HtmlDecode(s).Trim()
Evidently you can try to convert to spaces yourself. But there are examples where it is not that evident and your transcoder can get confused or decode strings the wrong way. Furthermore if in the future the people at W3C change their minds about how to encode text in HTML/XML, then your program will still work.
String.Trim will remove all kinds of white-space including spaces, new lines, tabs, carriage returns, etc. If you only want to remove spaces, you can use: .Trim(' '). Then you specify only to remove the given list of characters (here only ' ').

If you want to remove leading or trailing white-spaces from a string you just need to use String.Trim, but you have to re-assign the return value to the variable since strings are immutable:
string text = "إختر       ‎";
text = text.Trim();
Note that you can also use TrimEnd in this case.
If you want to remove only space characters(not also tabs or new-line characters which are also white-spaces) use:
text = text.Trim(' ');
If you instead want to remove all spaces from a string you could do:
text = text.Replace(" ", "");

I think maybe your code is something like this
Dim str As String = "إختر "
str.Replace(" ", "")
But actually you should
Dim str As String = "إختر "
str = str.Replace(" ", "")

I have just had a similar problem.
It turns out, that this nbsp character is Chr(160) from the ASCII table. Thus, something like this is quite meaningful, for all the cases. It works, on a selected area:
Public Sub remove_space_in_string()
Dim r_range As Range
For Each r_range In Selection
r_range = Trim(r_range)
r_range = Replace(r_range, vbTab, "")
r_range = Replace(r_range, " ", "")
r_range = Replace(r_range, Chr(160), "")
Next r_range
End Sub

Related

Remove spaces on new line, but keep the line

I wish to remove spaces from lines that doesn't contain text, but not remove the line. Since a space character can be hard to identify, I will replace the space character with the "#" (hastag character) to showcase the example easier. The string looks something like this:
"This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
I wish that the output would remove the spaces on the lines that only contains the space character. I am still using the "#" (hastag character) to showcase the spaces. The final output should look like this:
"This is
########a long string
with many lines
and the above is empty
####this is empty
#######hello"
Without the hashtag character acting as the space character, the expected output should look like this:
"This is
a long string
with many lines
and the above is empty
this is empty
hello"
So to fully clarify, I wish to remove space characters on a line that doesn't contain text, but not remove the line.
Using your example with octothorpes (yet another name for #) and replacing them with spaces in the code, we can use the String.IsNullOrWhiteSpace function to check for such lines and replace them with empty strings:
Module Module1
Sub Main()
Dim s = "This is
########a long string
with many lines
#######
and the above is empty
####this is empty
#############
#######hello"
s = s.Replace("#", " ")
Dim t = String.Join(vbCrLf, s.Split({vbCrLf}, StringSplitOptions.None).
Select(Function(a) If(String.IsNullOrWhiteSpace(a), "", a)))
Console.WriteLine(t)
Console.ReadLine()
End Sub
End Module
Outputs:
This is
a long string
with many lines
and the above is empty
this is empty
hello
Use the following code:
Dim container As String = IO.File.ReadAllText("test.txt")
container = container.Replace(vbNewLine, vbCr).Replace(vbLf, vbCr)
Do While container.Contains(vbCr & vbCr)
container = container.Replace(vbCr & vbCr, vbCr)
Loop
If container.StartsWith(vbCr) Then container = container.TrimStart(Chr(13))
container = container.Replace(vbCr, vbNewLine)
IO.File.WriteAllText("test.txt", container)
It'll trim all the empty new lines and override the file (before vs. after):
Note: If you want to remove the hashes and replace that with white spaces too, just use the following:
Dim container2 As String =
My.Computer.FileSystem.ReadAllText("test.txt").Replace("#", " ")
IO.File.WriteAllText("test.txt", container2)
Try this
Dim myString = "your multiline string here"
Dim finalString As String
For each line In myString.Split(CChar(vbNewLine))
finalstring &= line.Trim() & vbNewLine
Next

How to remove non-alphabetical characters from a string?

I am looking for a way to remove characters from any string that are not alphabetical characters.
I am basically just using Replace for every non-Alphabetical character. This method would take forever.
I guess I could make an array (I think) but that would still take quite a while. Is there any simple solution?
Dim wordy As String = textBox.Text.ToUpper.Replace(".", "").Replace("!", "").Replace(" ", "").Replace("'", "").Replace("?", "") _
.Replace(",", "").Replace("-", "")
The following lines of code should help.
MsgBox(Regex.Replace(s, "[^a-zA-Z ]", ""))
This will keep only upper/lowercase A-Z as well as spaces.
Your example,
Dim wordy As String = textBox.Text.ToUpper.Regex.Replace(s, "[^a-zA-Z ]", "")
You could also just use a MaskedTextBox that would allow only numeric input based on the mask.
This will remove all characters except A-Z in lower and upper case, as well as spaces. If you want spaces to be removed, remove the space from the end of the regular expression.
Dim rgx As New Regex("[^a-zA-Z ]")
Dim wordy As String = rgx.Replace(textBox.Text,"")

Remove excess white space from string

I want to remove the excess white spaces using VB.net
ex.
"The Quick Brown Fox"
I want output
"The Quick Brown Fox"
Thanks,
inchika
You can use a simple regular expression for that:
Dim cleaned As String = Regex.Replace(input, "\s{2,}", " ")
I realize that this question is fairly old, but there is another option that doesn't involve Regex, or manually looping through the string and replacing:
Private Function StripSpaces(input As String) As String
Return String.Join(" ", input.Split(New Char() {}, StringSplitOptions.RemoveEmptyEntries))
End Function
And the C# equivalent:
private string StripSpaces(string input)
{
return string.Join(" ", input.Split((char[])null, StringSplitOptions.RemoveEmptyEntries));
}
Using a "null" value as the split character on String.Split causes the split character to be all characters that return true if they were sent to Char.IsWhiteSpace. Therefore, calling the method this way will split your string on all whitespace, remove the empty strings, then re-join it together with a single space in between each split array element.
What you actually want is to compact any multiple white space to a single space, and one way to do that is to search for two spaces and replace them with a single space, until there are no two adjascent spaces left, something like this:
Dim myString As String = "The Quick Brown Fox"
While myString.IndexOf(" ") <> -1
myString = myString.Replace(" ", " ")
End While
Console.WriteLine(myString)
However, this is not fool-proof because of some ideosyncracies of .net strings, this might go into an endless loop, but only for some very odd inputs.
EDIT: This particular processing is faster (and simpler) using a regular expression, as pointed in the othe answers.
Try this:
Dim output As String = Regex.Replace("The Quick Brown Fox","\\s+" , " ")

Remove special characters from a string

These are valid characters:
a-z
A-Z
0-9
-
/
How do I remove all other characters from my string?
Dim cleanString As String = Regex.Replace(yourString, "[^A-Za-z0-9\-/]", "")
Use either regex or Char class functions like IsControl(), IsDigit() etc. Get a list of these functions here: http://msdn.microsoft.com/en-us/library/system.char_members.aspx
Here's a sample regex example:
(Import this before using RegEx)
Imports System.Text.RegularExpressions
In your function, write this
Regex.Replace(strIn, "[^\w\\-]", "")
This statement will replace any character that is not a word, \ or -. For e.g. aa-b#c will become aa-bc.
Dim txt As String
txt = Regex.Replace(txt, "[^a-zA-Z 0-9-/-]", "")
Function RemoveCharacter(ByVal stringToCleanUp)
Dim characterToRemove As String = ""
characterToRemove = Chr(34) + "#$%&'()*+,-./\~"
Dim firstThree As Char() = characterToRemove.Take(16).ToArray()
For index = 1 To firstThree.Length - 1
stringToCleanUp = stringToCleanUp.ToString.Replace(firstThree(index), "")
Next
Return stringToCleanUp
End Function
I've used the first solution from LukeH, but then realized that this code replaces the dot for extension, therefore I've just upgraded the code slightly:
Dim fileNameNoExtension As String = Path.GetFileNameWithoutExtension(fileNameWithExtension)
Dim cleanFileName As String = Regex.Replace(fileNameNoExtension, "[^A-Za-z0-9\-/]", "") & Path.GetExtension(fileNameWithExtension)
cleanFileName will the file name with no special characters with extension.

replace " in vb.net

How can I replace the double quote in VB.NET?
This code doesn't work:
name.Replace("""," ")
You need to use a double quote within those quotes (and get the return value - String.Replace does not operate on the string itself, it returns a new string):
name = name.Replace(""""," ")
Instead of a "data link escaped" method of...
name = name.Replace("""", "")
You could be explicit and somewhat more readable...
name = name.Replace(ControlChars.DblQuote, "")
And BTW, instead of thinking of this as returning a NEW STRING; it's better to think of the REPLACE as a part of the STRING Class associated with the 'name' instance. If it's losing the old value of name that you do not want then simply...
Dim aNewString$ = name.Replace(ControlChars.DblQuote, "")
And the 'name' will remain unchanged.
name = name.Replace(Chr(34), "")
you should return the resultant string back to a string and also escape that double quotes with a double quote or "\"
name = name.Remove("""", String.Empty)
I had a nasty one where try as I might, I could not get Replace() to work. In the end, it turned out the strings I was trying to clean somehow had got a completely different characters which just LOOKED like double quotes. A genius had edited a script file using Word, so "hello" became “hello”. Subtle, or what?
Looking at the file with a hex editor, the opening quote was the three character value 0xe2 0x80 0x9c, and the closer was 0xe2 0x80 0x9d. No wonder the replace failed!
'This part is to remove the " mark in the string
Dim GetDate31 As String = Date31(16).Replace(Chr(34), "")