How does this line of VB.NET code work? - vb.net

I am using VB.NET and String.Format.
The line of code below populates s with 20 space characters. The problem is that I don't know how it works and can't find an explanation. Reference: MSDN String.Format Method.
Dim s As String = String.Format("{0, 20}", String.Empty)
It gives me the result I need, a string populated with with 20 space characters, but what is the "0"? If I change that to any other num it creates an error.
And I don't see where / how it's specifying a Space char?

The format specififer {0, 20} indicates that it will place your object string.Empty as element {0} at the end of an empty 20 character string. By that I mean that your item will be used to fill the right side of a 20 character string and the remainder will be padded. Since you're using string.Empty you get a completely blank string. Try adding z and changing the number to a negative number.
string.Format("{0, -10}", "z");
This should give you a 10 character string starting with z and filled with spaces. This is default behavior for string.Format, and it is most commonly used when formatting custom numerics. The space doesn't need to be included as part of the command because that's considered expected by the fact that your specifier indicated you wanted a result string of 20 characters. Space seems the most logical inserted default character.
If you use a complex string like:
string.Format("{0, 10}", "abc");
You should still get a 10 character string but it will look like
" abc"

The 0 in the first parameter is the index of the argument.
The signature of that method is String.Format(string format, object[] params).
So "{0, 20}" is the string to be formatted, and everything else is turned into an object array.

the zero is the index of the parameter that you are sending, in your case String.Empty

Related

string and numeric value when equal returns true

Why does 5.5 = "5.5" return true in VBA?
Is it an acceptable practice to direclty compare numeric values to string values in vba?
This returns true
if 5.5 = "5.5" Then ...
This might get shut-down as opinion-based more than anything, but I would say that YES it is acceptable. It is often used when comparing cell values to numbers, or adding cell values, for example. IE If my cells contain a string such as abcde123, and i only want to use the 123, I could only take the 3 right characters of the string and use them directly. If you want to be very rigorous you could use Cint(string) but i do not think it is necessary.
It looks like VBA converts the string to a Double and compares. From the page on comparison operators
If operands are: One numeric and one String
Comparison Is: The String is converted to a Double and numeric comparison is performed. If the String cannot be converted to Double, an InvalidCastException is thrown.

VB.NET - Substring function that stops reading at first integer, possible?

I currently have a text file that has a little over 500 lines of paths.
(i.e., N:\Fork\Cli\Scripts\ABC01.VB)
Some of these file names vary in length (i.e., ABC01.VB, ABCDEF123.VB, etc)
How can I go about using substring function to remove the path name, numbers, and file type, leaving just the letters.
For example, processing N:\Fork\Cli\Scripts\ABC01.VB, and returning ABC.
Or N:\Fork\Cli\Scripts\ZUBDK22039.VB and returning ZUBDK.
I've only been able to retrieve the first 3 letters using this code
Dim comp As String = sLine.Substring(28, 3)
sw.WriteLine(comp)
As Plutonix points out, the best way to isolate the file name from a path is with System.IO.Path.GetFileNameWithoutExtension.
You can extract just the letters (not digits or other characters) from a filename like this:
Dim myPath As String = "N:\Fork\Cli\Scripts\AB42Cde01.VB"
Dim filename As String = System.IO.Path.GetFileNameWithoutExtension(myPath)
Dim letters As String = filename.Where(Function(c) Char.IsLetter(c)).ToArray
The above code sets letters to ABCde.
The code relies on the fact that Strings are treated like arrays of characters. The Where method processes all the characters in the string (array) and selects only the ones that are letters (using the Char.IsLetter method). The selected characters are converted to an array (string) that is assigned to the letters variable.
I see from your latest comment that it is not possible for numerals to be mixed with the letters (as in my example). However, the code should still work in your case.

String Manipulation Inconsistency

This is a more general question. I am reading a document and saving its contents into a string variable. The resulting variable contains approximately 1 million characters (no cleansing). My code would then search the string, and extract key words. However, I am hung-up on an issue:
If I pass the string directly to a message box, it will show me the contents using Mid:
Messagebox.Show(Mid(searchString, startPos, endPos))
However, if I first pass the mid to a string variable, the contents are empty and the messagebox displays nothing:
Dim myString as String
myString = Mid(searchString, startPos, endPos)
Messagebox.Show(myString)
The same effect happens when I use .substring and when I use a stringbuilder.
Does anybody know why this is happening? I assume something is happening during assignment, but I am not sure what is lost?
Here is a snippet of code:
searchPos = textString.IndexOf(searchText, searchPos, StringComparison.OrdinalIgnoreCase)
MessageBox.Show(searchPos)
MessageBox.Show(Mid(textString, searchPos, 100))
So, the inconsistency is as such: the length of textString is around 3,700,000 characters. When I find the indexOf, the value returned in the first Messagebox is 455,225. However, if I try to pull out the characters using Mid, the second messagebox is blank.
Also, although it claims to be 3,700,000 characters, if I do a messagebox on textString, I am only shown around 6 characters of what appears to be XML. The file that is being searched is an old .ppt file, and I know I can just work-around it, but I am confused by how the computer can find the indexof my searchText correctly, but then cannot show me anything.
Thoughts?

How to get the amount of characters in a label (VB)

I've looked everywhere, but I can't find how to do this in VB
The text of a label is a String. Strings have a Length property, which returns the number of characters in the string. Thus, the following should work:
numberOfCharacters = myLabel.Text.Length

Can't trim periods (...) and ellipsis (...) from strings in vb.net

I'm getting a very strange result when I try to use string.trim to remove characters.
I want to remove leading and trailing periods (...) from strings, but my code only removes trailing characters for some reason. Microsoft's documentation says that the string.trim(char array) method should trim from the start and end of the string.
http://msdn.microsoft.com/en-us/library/zke31k1x.aspx
My code to trim the string is...
mystring=mystring.trim(".")
if the input is "2342...." it gets shortened to "2342" but if the input is "...2342" the output is still "...2342"
I've tried defining a character array with 1 member (i.e. "."), but I get the same result.
I've also tried mystring.trimstart(".") but it does not work either
I'm pretty confused about why I'm getting this behavior
EDITED/SOLVED:
mystring included two different characters that represent dots (.)
One of the characters in mystring was three dots as an ellipsis (the three together were encoded as a single character with a value of 133). The other was a simple period (value of 46).
This solves the problem:
mystring=mystring.Trim(Chr(133)) 'removes ellipsis
mystring=mystring.Trim(Chr(46)) 'removes periods
I tried it right now:
Dim mystring = "...2342"
mystring = mystring.Trim(".")
Console.WriteLine(mystring)
but result is always 2342.
Are you sure that first char in "...2342" is a "."? Did you check its ASCII value?
Which framework are you using? I'm using Framework 4.0.
EDITED: try this to get ascii values
For Each c As Char In mystring.ToCharArray()
Console.Write(Hex(Asc(c)) & "-")
Next
Console.WriteLine()
Just tried this:
Dim mystring = "...2342"
mystring = mystring.Trim(".")
mystring is always 2342 no matter what permutation I try.
Have you definetly checked the result correctly? You're not checking it in break mode before the operation has taken place?
I agree with #Marco, perhaps the "." you used was not the same as the input.