VB2010 String adds up Length by adding "" - vb.net

I'am comparing Strings in Visual Basic 2010 Express. While cuting the String together it sometimes adds a Char with "", what I hoped is "nothing"
Example:
Dim text as String = "test"
Dim sign as Char = ""
text = text + sign
while debuging it says that the new text is "test", but if I ask for the Length it is 5.
This is a problem when I try to compare this with an other String
Dim bigtext as String = "test1234"
Dim text as String = "test"
Dim sign as Char = ""
text = text + sign
bigtext.indexOf(text) 'should be 0 (index), but is -1 (not found)
any idea how to filter a "" away or any other workaround?
Edit - my workoround for now:
Now I add "§" everywhere instead of "" and when I need to use indexOf() to compare something, I Replace("§", "") it.
(with Replace() it is deleted)

As far as I can see, a Char variable always has a character in it (which can be the null character). Concatenating it to another string will append that character to the existing string.
I see two workarounds:
Use a String for sign instead of a Char. The string could be empty or have a single character in it.
Trim the undesired character from the resulting string:
text = (text + sign).Trim(CChar(""))

Related

how to parse string containing Unicode ID's as well as plain text for display in datagrid view [duplicate]

This question already has answers here:
How do I convert Unicode escape sequences to Unicode characters in a .NET string?
(5 answers)
Closed 3 years ago.
I am trying to parse a string (returned by a web server), which contains non-standard (as far as I can tell) unicode Id's such as "\Ud83c" or "\U293c", as well as plain text. I need to display this string, emojis in tact, to the user in a datagrid view.
btw, I am blind so please excuse any formatting errors :(
full example of what my code is parsing: "Castle: \Ud83d\Udc40Jerusal\U00e9m.Miles"
the code I wrote which is failing miserably:
Public Function ParseUnicodeId(LNKText As String) As String
Dim workingarray() As String
Dim CurString As String
Dim finalString As String
finalString = ""
' split at \ char
workingarray = Split(LNKText, chr(92))
For Each CurString In workingarray
If CurString <> "" Then
' remove leading U so number can be converted to hex
CurString = Right(CurString, Len(CurString) - 1)
' attempt to cut off right most chars until number can be converted to text as there is nothign separating end of Unicode chars and start of plain text
Do While IsNumeric(CurString) = False
If CurString = "" Then
Exit Do
End If
CurString = Left(CurString, Len(CurString) - 1)
Loop
If CurString.StartsWith("U", StringComparison.InvariantCultureIgnoreCase) Then
CurString = CurString.Substring(1)
End If
' convert result from above to hex
Dim numeric = Int32.Parse(CurString, NumberStyles.HexNumber)
' convert to bytes
Dim bytes = BitConverter.GetBytes(numeric)
' convert resulting bytes to a real char for display
finalString = finalString & Encoding.Unicode.GetString(bytes)
End If
Next
ParseUnicodeId = finalString
End Function
I tried to do this all kinds of ways; but can't seem to get it right. My code currently returns empty strings, although my guess is that is because of some of the more recent changes I have made to cut off the leading U or to try and chop off one char at a time. If I take those bits out and just pass it something like "Ud83c", it works perfectly; its only when plain text is mixed in that it fails, but I can't seem to come up with a way to separate the two and re-combine at the end.
You can use Regex.Unescape() to convert the unicode escaped char (\uXXXX) to a string.
If you receive \U instead of \u, you also need to perform that substitution, since \U is not recognized as a valid escape sequence.
Dim input as String = "Castle: \Ud83d\Udc40Jerusal\U00e9m.Miles"
Dim result As String = Regex.Unescape(input.Replace("\U", "\u")).
This prints (it may depend on the Font used):
Castle: 👀Jerusalém.Miles
As a note, you might also have used the wrong encoding when you decoded the input stream.

How to add spaces for certain condition using vb.net?

Let say, maximum length in textbox1 is 6 digits. so if the user enter less than 6, i want to add spaces in front of the text. I have no idea how to do that.
Example:
TextBox1 = "123"
output = " 123"
System.String has a method called PadLeft - it adds whatever char you want to the left of the string to make it whatever length you choose:
Dim str As String
Dim pad As Char
str = "123"
pad = "."c ' Using dots instead of spaces so you can see it...
Console.WriteLine(str)
Console.WriteLine(str.PadLeft(6, pad))
Result:
123
...123
You can see a live demo on rextester.
BTW, it also has PadRight...

remove from String in VB

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

How to Xor a string with a password?

This is what I have so far.
Public Function XOREncDec(ByVal textToEncrypt As String) As String
Dim inSb As New StringBuilder(textToEncrypt)
Dim outSb As New StringBuilder(textToEncrypt.Length)
Dim c As Char
For i As Integer = 0 To textToEncrypt.Length - 1
c = inSb(i)
c = Chr(Asc(AscW(c)) Xor "password")
outSb.Append(c)
Next
Return outSb.ToString()
End Function
However I am getting an error here
c = Chr(Asc(AscW(c)) Xor "password")
"Conversion from string "password" to type 'Long' is not valid."
First, read the comments about better methods to protect strings.
Then, we can look at your code. You would xor characters with one character at a time from the password, not the whole password. You can use the loop variable with the mod operator to get the corresponding index in the password so it will repeat the characters in password along the length of the string.
Using Asc(Ascw(c)) means that you get the character code for the first character of the string representation of the character code for the character. For example the character A would give you the character code 65, that would implicitly be converted to the string "65" to get the character code for the character 6, which is 54. As you only use the first digit of the character code, it would not be possible to get the original string back.
You should use ony AscW to get the character code, and then ChrW to turn the adjusted character code back to a character. The Asc and Chr function doesn't support Unicode characters.
You don't need a StringBuilder for the input, you can access the characters directly from the string.
Public Function XOREncDec(ByVal textToScramble As String) As String
Dim builder As New StringBuilder(textToScramble.Length)
Dim password As String = "password"
Dim c As Char
For i As Integer = 0 To textToScramble.Length - 1
Dim pos As Integer = i mod password.Length
c = textToScramble(i)
c = ChrW(AscW(c) Xor AscW(password(pos)))
builder.Append(c)
Next
Return builder.ToString()
End Function
Note that I renamed the parameter from textToEncrypt to textToScramble, as this simple encoding can't be called encryption in any modern sense of the word.
A word of caution also, the string that is the result of encoding will often contain character codes that doesn't correspond to real characters. It works as long as you decode the same string object, but if you for example write the string to a file and then try to read it back, it will most likely get corrupted. To get data that would survive any kind of storage or communication, you would encode the string into bytes, scramble the bytes, and then create a string value from the bytes using for example base64 encoding.

VB.NET Get text in between Quotations or other symbols

I want to be able to extract a string in between quotation marks or parenthesis etc. to a variable. For example my text might be "Hello there "Bob" ". I want to extract the text "Bob" from in between the two quotation marks and put it in the string "name" for later use. The same would be for "Hello there (Bob)". How would I go about this? Thanks.
=======EDIT======
Sorry, I worded this poorly. Ok, so lets say I have a textbox(Textbox1) and a button. If the user inputs the text: MsgBox "THIS IS MY MESSAGE" I want that when the Button is pressed, only the text THIS IS MY MESSAGE is displayed.
This is a solution very simple:
Dim sAux() As String = TextBox1.Text.Split(""""c)
Dim sResult As String = ""
If sAux.Length = 3 Then
sResult = sAux(1)
Else
' Error or something (number of quotes <> 2)
End If
There are basically three methods -- regular expressions, string.indexof and substring and finally looping over the characters one by one. I would avoid the latter as it is just reinventing the wheel. Whether to use regexs or indexof depends upon the complexity of your requirements and data. Indexof is a bit wordy but fairly straightforward and possibly just what you want in this case.
Dim str as String = "Hello there ""Bob"""
Dim startName as Integer
Dim endName as Integer
Dim name as String = ""
startName = str.IndexOf("""")
endName = str.Indexof("""", If(startName > 0, startName,0))
If (endName>startName) Then
name = str.SubString(startName, endName)
End If
If you need to do this for arbitrary symbols, then you want regexs.