hi,
Can anyone show how to count a string
for example:
dim a as string
a = "abcdefghij"
how can i count the string above
the answer should be 10.:confused:
Printable View
hi,
Can anyone show how to count a string
for example:
dim a as string
a = "abcdefghij"
how can i count the string above
the answer should be 10.:confused:
The String object is a class that has methods and properties. One of the properties of the String class is Length, which returns the length of the string.
When you type "a." you should get a list of methods and properties that are publicly available from that object. A lot of the time, you can find things like this yourself by just looking through the names of the properties and methods.
thanks for the answer..
but how can i eliminate the space between the string?
dim a = "abc def ghij"
the answer should be 10 also..
i using trim function but it doesn't work
any idea?
If you want to get rid of a space you can Replace a space with a blank string.
Here's some code. It uses a textbox, label and button on a form.
Code:Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim NumberOfCharacters, IndexOfSpace As Integer
str = TextBox1.Text
str = str.Trim ' First remove leading and following spaces from string.
Do Until str.IndexOf(" ") = -1 ' If " " isn't in the string then str.IndexOf(" ") will give a value of -1
IndexOfSpace = str.IndexOf(" ") ' Loop until there are no spaces in string
str = str.Remove(IndexOfSpace, 1)
Loop
NumberOfCharacters = str.Length
Label1.Text = "There are " & NumberOfCharacters & " characters in " & str & "."
End Sub
End Class
' You may want to ignore other characters also:
Public Class Form1
' Ignore spaces, newlines, and tabs
Dim IgnoreChar As String = _
ControlChars.Tab & ControlChars.Cr & ControlChars.Lf & " "
Dim TestString As String = _
"ab c" & ControlChars.Tab & "d" & ControlChars.NewLine & "e"
Dim count As Integer = 0
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
count = 0
Dim CharacterToInspect As Char
For StringPosition As Integer = 1 To TestString.Length
CharacterToInspect = GetChar(TestString, StringPosition)
If Not IgnoreChar.Contains(CharacterToInspect) Then
count += 1
End If
Next
MsgBox(count) ' Answer = 5
End Sub
End Class
thnks guy :thumb:
You are absolutely right Negaivo. That one line of code does what Trim and the Do Loop does. I wasn't aware of Replace. Is that something new to Visual Basic 2008 or perhpas 2005?