I have a byte array that I convert into a string like so Dim byt As Byte() = New Byte(255) {} s = New String(Encoding.ASCII.GetChars(byte))
My question is when I look at the string in a debuger its clearly a normal string but when I compare it to what I know its supposed to be it doesnt equal. So i did a quick check and for some reason its return a string thats the length of 256 characters. So i did a s.trim and it still is 256 characters long. Any idea whats going on what this?
You created a string with 256 characters that are 0. The debugger cannot display them. Use this to trim the string:
s = s.Trim(ChrW(0))
Related
I have a function that convert string to ascii code (e.g string = "system" the value of string in ascii = "115 121 115 116 101 109") and what i need is a way to convert the `ascii into char. Do i need to use loop to filter the converted ascii ? I need your suggestion what is the best way to convert it
The best way is one that checks your assumptions. You say the string contains ASCII bytes. So if someone slips in a byte that cannot be ASCII, you should be told. It does appear that someone slipped in an unexpected space, but that can be ignored.
Imports System.Linq
'…
Dim asciiEncoding = Encoding.GetEncoding("US-ASCII",
EncoderFallback.ExceptionFallback,
DecoderFallback.ExceptionFallback)
Dim ascii = "115 121 115 116 101 109"
Dim asciiBytes = ascii.Split( { " "c }, StringSplitOptions.RemoveEmptyEntries) _
.Select(Function (s) Byte.Parse(s)) _
.ToArray()
Dim s = asciiEncoding.GetString(asciiBytes)
Other ways might not catch invalid data.
Some ways automagically convert from the ASCII character set to the Unicode character set, which is valid when the data is, in fact, ASCII but at least deserves a comment about the conversion and that the data is trusted to be ASCII.
Speaking of whether the data is ASCII or not, there is no text but encoded text. When you read text, you have to use the encoding it was written with. The only way to know is for the writer to make it known.
My suggestion is:
First split the string using string.split(' ');
And then convert each split string to char like this:
foreach(string word in SplitedWords)
{
Convert.ToChar(int.Parse(word));
}
This is built-in. You can treat a String as an array of Char.
Dim s As String = "system"
Console.WriteLine(s(4) & " = ASCII " & Asc(s(4))) 'output: e = ASCII 101
Console.ReadKey()
You can use the Asc() function to get the ASCII value of the character, but be aware that Strings and Chars are actually Unicode, not ASCII. Depending on encoding, you might find that one character is more than one byte.
FOR THE NITPICKERS: When you treat a String as an array of Char, the compiler boxes the String, so it is less efficient that having a true Char array.
I have an application that makes a call to a third party web API that returns a String that looks something like this:
"JVBERi0xLjMNCiXi48/TDQoxIDAgb2JqDQo8PA0KL1R5cGUgL091dGxpbmVzDQovQ291bnQgMA0KPj4NCmVuZG9iag0KMiAwIG9iag0KDQpbL1BERiAvVGV4dCAvSW1hZ2VDXQ0KZW"
(It's actually much longer than that but I'm hoping just the small snippet is enough to recognize it without me pasting a string a mile long)
The documentation says it returns a Byte array but when I try to accept it as a Byte array directly, I get errors. Part of my problem here is that the documentation isn't completely clear what the Byte array represents. Since it's a GetReport function I'm calling, I'm guessing it's a PDF but I'm not 100% sure as the documentation doesn't say at all.
So, anyway, I'm getting this String and I'm trying to convert it to a PDF. Here's what that looks like:
Dim reportString As String = GetValuationReport(12345, token.SecurityToken)
Dim report As Byte() = System.Text.Encoding.Unicode.GetBytes(reportString)
File.WriteAllBytes("C:\filepath\myreport.pdf", report)
I'm pretty sure that the middle line converts the String into a new Byte array rather than simply converting it into its Byte array equivalent but I don't know how to do that.
Any help would be fantastic. Thanks!
It looks like your string may be Base64 encoded, in which case you would use this to convert it to bytes:
Dim report As Byte() = Convert.FromBase64String(reportString)
this is my code to convert string to hex
Function StringToHex(ByVal text As String) As String
Dim xhex As String
For i As Integer = 0 To text.Length - 1
xhex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
Next
Return xhex
End Function
I convert string file to hex with this code, but if size file more than 1MB my program is not responding
how to make this code more efficient for size file more than 1MB sorry my english is bad
As I said in my initial comment, your current approach is creating a new string each time you go through the For loop. Strings are immutable (can't be changed) in .NET - so for example if you have 3000 characters in the string, xHex = &a is going to create 3,000 strings, and that's just for the first part. Then you have a Substring, then a ToString and finally a ToUpper - so if my math is right, you're creating 4 strings for every character in the input string (so if you have 3,000 characters that 12,000 additional strings).
The call to Substring is unnecessary - you can treat the string as an array and access each character in the string as an array index, so now you would have:
xhex &= Asc(text(i)).ToString("x").ToUpper
You can also get rid of the call .ToUpper() by using an uppercase "X" in the call to .ToString() - so now you have:
xhex &= Asc(text(i)).ToString("X")
You could also make xhex a StringBuilder, and then you'd only be creating one additional string each time through the loop (the call to .ToString()). Putting that all together gives you this:
Dim xhex As StringBuilder = New StringBuilder()
For i As Integer = 0 To text.Length - 1
xhex.Append(Asc(text(i).ToString("X"))
Next
Return xhex.ToString()
That may help with the process, but if the string is really large you may still run into memory issues. IF the file is really large I'd recommend reading it using a Stream and processing the Stream one byte at a time (or several bytes at time, your choice).
I would also suggest Googling for VB.NET convert string to hex, as there are many examples of other ways to do this.
I would like to create a stringbuilder with the length of 256, and the string "128" should be placed at the start.
However, my code
Dim sb As New StringBuilder
sb.Append(New String("128", 256))
Dim s As String = sb.ToString
shows me that all 256 chars are filled with "1":
s = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
Can somebody tell me what I did wrong?
Thank you!
If I'm reading your question right, this should do what you want:
Dim sb As New StringBuilder(256)
sb.Append("128")
Or did you want spaces?
Dim sb As New StringBuilder("128".PadRight(256))
The 256 in the StringBuilder constructor is a performance optimization. Since you know the length of the resulting string, go ahead and reserve all the space for it up front. It's also possible you'll be doing a lot more work to this string, such that a different (larger) number or no number may be appropriate there.
Based on the comment:
Dim sb As New StringBuilder("128".PadRight(256, NullChar()))
But this is a really bad idea. Don't use nul characters in .Net.
What you did wrong was assume what New String("128", 256) does. If you look at the nearest available constructor: String Constructor (Char, Int32) you will see it takes a Char. This means it ends up repeating the first char, 1, 256 times.
The way you appear to want to do it could be realised using
Dim sb As New StringBuilder("128")
sb.Length = 256
because according to the documentation on the StringBuilder.Length Property: "If the specified length is greater than the current length, the end of the string value of the current StringBuilder object is padded with the Unicode NULL character (U+0000)."
Hey guys I'm stuck with this question. Please help.
I want to write a program that can extract alphabetical characters and special characters from an input string. An alphabetical character is any character from "a" to "z"(capital letters and numbers not included") a special character is any other character that is not alphanumerical.
Example:
string = hello//this-is-my-string#capetown
alphanumerical characters = hellothisismystringcapetown
special characters = //---#
Now my question is this:
How do I loop through all the characters?
(the for loop I'm using reads like this for x = 0 to strname.length)...is this correct?
How do I extract characters to a string?
How do I determine special characters?
any input is greatly appreciated.
Thank you very much for your time.
You could loop through each character as follows:
For Each _char As Char In strname
'Code here
Next
or
For x as integer = 0 to strname.length - 1
'Code here
Next
or you can use Regex to replace the values you do not need in your string (I think this may be faster but I am no expert) Take a look at: http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx
Edit
The replacement code will look something as follows although I am not so sure what the regular expression (variable called pattern currently only replacing digits) would be:
Dim pattern As String = "(\d+)?" 'You need to update the regular expression here
Dim input As String = "123//hello//this-is-my-string#capetown"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, "")
Since you need to keep the values, you'll want to loop through your string. Keeping a list of characters as a result will come in handy since you can build a fresh string later. Then take advantage of a simple Regex test to determine where to place things. The psuedo code looks something like this.
Dim alphaChars As New List(Of String)
Dim specialChars As New List(Of String)
For Each _char As Char in testString
If Regex.IsMatch(_char, "[a-z]")) Then
alphaChars.Add(_char)
Else
specialChars.Add(_char)
End If
Next
Then If you need to dump your results into a full string, you can simply use
String.Join(String.Empty, alphaChars.ToArray())
Note that this code makes the assumption that ANYTHING else than a-z is considered a special character, so if needs be you can do a second regular expression in your else clause to test for you special characters in a similar manner. It really depends on how much control you have over the input.