Sie sind auf Seite 1von 8

Handling Strings

What is a string?
A string is a series of alphanumeric characters enclosed in quotation marks.
A string is data type that stores one or more characters, which can be
alphabetic or alphanumeric.
If a variable is declared as a string, it must not be used for daily life
mathematical calculations because strings are not numbers.
A string is sometimes just referred to as text. Any type of alphabetic or
numeric data can be stored as a string: Birmingham City, 3/10/03 and
36.85 are all examples of strings.
Each character within a string will be stored in one byte using its ASCII code;
modern systems might store each character in two bytes using its Unicode.
The maximum length of a string is limited only by the available memory.
Declaration of strings
Dim Name As String
If a value of string variable is assigned within the program code, it must be
enclosed in quoates e.g.
Name = Agrippa
Name =
The second example will be a null (un-initialised) string. It is different from 0 or
space but is distinct in nature.
Strings can be of fixed length or variable length


Variable length string
Variable length string
Dim Surname As String
Variable length does not specify the number of
characters, each data items occupies the number
of spaces it requires.
This is declared as follows
Dim Sname as string

Fixed length string
Fixed length string
Dim StudentNumber As String * 5
Fixed length: has specified maximum number of characters. E.g.
Dim Sname as string * 20
The field will be allocated 20 spaces in the computer memory.
If a name shorter than 20 characters is entered, blank spaces will
remain unoccupied since they would have been assigned to Sname
already.
If too long than allocated space, the extra characters are cut.

Processing strings: Sorting
Using relational operators.
if Name1< Name2 then
Print Name1 & & Name2
else
Print Name2 & & Name1
end if
Processing Strings contd
Count number of characters in a string using len
The function Len returns the number of characters stored in a string passed to
it.
Syntax: CharacterNumber = len(string) then Print CharacterNumber
Print Len(string)
Question:
Design a program in VB to capture five names of computer science students
and count the number of characters in each student name. the program should
display the student name and in front of it, the number of characters
E.g. Mungazi Davies This name has 14 characters
VB code
Dim Spaces As Integer
Dim EmployName As String
Dim Index As Integer
Dim Charater As String * 1
EmployeeName = txtName.text
Spaces = 1
For index = 1 to Len(EmployeeName)
Character = Mid(EmployeeName, Index)
If character = then
Spaces = Spaces + 1
End if
Next Index
If Spaces >= 2 then
Msgbox (too many spaces), vbExclamation

Das könnte Ihnen auch gefallen