PDA

Click to See Complete Forum and Search --> : Format string in VB.NET ??


Borry
Sep 27th, 2002, 06:49 AM
Hello everybody,


in VB6, I did the following :

myStr = format("hello","@@-@@-@") to receive this : he-ll-o

I really can't seem to find it in VB.NET :confused:

can anyone help me out please ??

Thanks a lot !

Bjorn

Tryster
Sep 27th, 2002, 07:32 AM
Try String.Format

Borry
Sep 27th, 2002, 07:41 AM
I've been trying it out but can't find a solution within the help

Edneeis
Sep 27th, 2002, 10:41 AM
Format seem to mainly format things that aren't text into some form of text. There isn't much to change the look of things that already are text it seems. BUT you can make your own Formatter to handle it. I'll try and find or make an example real quick.

Edneeis
Sep 27th, 2002, 11:45 AM
'in the application
Dim myStr As String = "hello"
myStr = String.Format(New AlphaFormat("@@-@@-@"), "{0} is how it looks in the new format", myStr)
'can also do it like this:
'myStr = String.Format(New AlphaFormat(), "{0:@@-@@-@} is how it looks in the new format", myStr)
MsgBox(myStr)

'the format class
Public Class AlphaFormat
Implements IFormatProvider
Implements ICustomFormatter

Private _format As String

' String.Format calls this method to get an instance of an ICustomFormatter to handle the formatting.
Public Function GetFormat(ByVal service As Type) As Object Implements IFormatProvider.GetFormat

If service.ToString() = GetType(ICustomFormatter).ToString() Then
Return Me
Else
Return Nothing
End If
End Function

' After String.Format gets the ICustomFormatter, it calls this format method on each argument.
Public Function Format(ByVal theformat As String, ByVal arg As Object, ByVal provider As IFormatProvider) As String _
Implements ICustomFormatter.Format

If theformat Is Nothing Then
'use _format
theformat = _format
End If

If theformat Is Nothing Then
Return String.Format("{0}", arg)
End If

If Not theformat.StartsWith("@") Then
' If the object to be formatted supports the IFormattable interface, then pass the format specifier to the objects ToString method for formatting.
If TypeOf arg Is IFormattable Then
Return CType(arg, IFormattable).ToString(Format, provider)
End If
' If the object does not support IFormattable, then call the objects ToString method with no additional formatting.
ElseIf (arg Is Nothing) Then
Return arg.ToString()
End If

Dim output As String
Dim c As Char
Dim cnt As Integer = 1
For Each c In theformat
If c = "@" Then
If arg.length >= cnt Then
c = Mid(arg, cnt)
cnt += 1
End If
End If
If c <> "@" Then
output &= c
End If
Next

Return output
End Function

Public Sub New(ByVal format As String)
mybase.New()
_format = format
End Sub

Public Sub New()
mybase.New()
End Sub

End Class