0% found this document useful (0 votes)
79 views26 pages

Unit 2 Variable:: Navin Malla Birendranagar 11 Airport Surkhet

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 26

Unit 2

Variable:
A variable is an identifier that denotes a storage area in the memory. For example
you can use a variable to store values, such as 3, 3.4, or Hello World. Every variable
has a type, which determines the values that can be store in to. A variable can store
different values during the execution of a program. Some examples of meaningful
variable names are salary, height, name, age and total_marks.
You should remember the following points while assigning a name to a variable in
Visual Basic 2010
A variable name can only contain alphabets, digit or numeric value.
A variable name should not begin with a digit or numeric value.
A variable name cannot contain a blank space.
Keywords cannot be used as variable names.
Declaring variables:
Variables are the names of the storage location. A variable can be used to store a
value of any data type. In Visual Basic 2010, by default, you must declare all
variables before using them. You can do that by using the Dim statement. Dim
statement is used to declare the data type of any variable in Visual Basic program
The general form of declaration of a variable is:
Dim variable1, variable2,,variableN As [New][ Type]
Some sample valid variable declarations are:
Dim Name, Address As String
Dim RollNo As Integer
A variable can be assigned a value at the time of its declared by using the = sign, as
shown in the following code snippet:
Dim Name As String="Rajendra"
Dim RollNo As Integer=1
Dim Grade As Char="A"

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

Variable names can be prefixed with string to indicate their data type. The use of
variable prefixes is optional. A list of some of the prefixed that have become
conventional for predefined data types in Visual Basic 2010 is given in table.
Table: Variable Prefixes
Data Type

Prefix

Boolean

Bin

Byte

Byt

Date

Dt

Double

Dbl

Error

Err

Integer

Int

Long

Lng

Object

Obj

Single

Sng

String

Str

Types of Variables
Youve learned how to declare variables and that all variables should have a type.
But what data types are available? Visual Basic recognizes the following five
categories of variables:
Numeric
String
Boolean
Date
Object
The two major variable categories are numeric and string. Numeric variables store
numbers, and string variables store text. Object variables can store any type of data.
Numeric Variables
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Youd expect that programming languages would use the same data type for
numbers. After all, a number is a number. But this could`nt be further from the
truth. All programming languages provide a variety of numeric data types, including
the following:
Integer (there are several Integer data types)
Decimal
Single (floating-point numbers with limited precision)
Double (floating-point numbers with extreme precision)
Integer Variables
There are three types of variables for storing integers, and they differ only in the
range of numbers each can represent. As you understand, the more bytes a type
takes, the larger values it can hold. The type of Integer variable youll use depends
on the task at hand.
String Variables
The String data type stores only text, and string variables are declared as follows:
Dim some Text As String
You can assign any text to the variable some Text. You can store nearly 2 GB of text
in a string variable (thats 2 billion characters, and its much more text than you care
to read on a computer screen). The following assignments are all valid:
Dim a String As String
A String = Now is the time for all good men to come to the aid of their country a
String =
A String = There are approximately 25,000 words in this chapter
A String = 25,000
Character Variables
Character variables store a single Unicode character in two bytes. In effect,
characters are Unsigned Short integers (UInt16), but the Framework provides all the
tools you need to work with characters without having to resort to their numeric
values (a very common practice for the older among us).
To declare a Character variable, use the Char data type:
Dim char1, char2 As Char

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

You can initialize a Char variable by assigning either a character or a string to it. In
the letter case, only the first character of the string is assigned to the variable. The
following statements will print the characters a and A to the Output window:
Dim char1 As Char = a, char2 As Char =ABC

Constant:
Constants are the names given to the values that do not change during the execution
of a program. A Constant is declared with the Const keyword, as shown in the
following code snippet.
Const pi=3.14159
In the preceding code snippet, we have created a constant, named Pi, with the value
3.14159.
eg:
Module Module1
Sub Main()
Const Pi = 3.14159
Dim Radius, Area As Single
Radius = 2
Area = Pi * Radius * Radius
Console.WriteLine("Area = " & Str(Area))
Console.ReadLine()
End Sub
End Module
Forcing variable declaration
undeclared variables name appears in your code, the editor will underline the
variables name with a wiggly line, indicating that it caught an error. The
description of the error will appear in the Task List window below the code window.
If you rest the cursor over the segment in question, you will see the description of
the error in a ToolTip box. To change the default behavior, you must insert the
following statement at the beginning of the file:
The Strict, and Explicit
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

The Visual Basic compiler provides three options that determine how it handles
variables:
The Explicit option indicates whether you will declare all variables.
The Strict option indicates whether all variables will be of a specific type.
Option Explicit Off
The Option Explicit statement must appear at the very beginning of the file. This
setting affects the code in the current module, not in all files of your project or
solution. You can turn on the Strict (as well as the Explicit) option for an entire
solution. Open the projects properties page (right-click the projects name in
Solution Explorer and select Properties), select the Compile tab, and set the Strict
and Explicit options accordingly,
Option Explicit Off
Public Class Form1
Public Const s As Integer = 100
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
var1 = "Thank you for using Fabulous Software"
var2 = 49.99
MsgBox("variable is " & var1.GetType().ToString())
MsgBox("variable is " & var2.GetType().ToString())
End Sub
End Class
Option Explicit Off
Option Strict Off ' allow to mix different datatype
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Dim a As Integer = 100


a = a + "1"
MsgBox(a)
Dim aa = 120
End Sub
End Class

Data Type
A data type determines the type of data that is stored in a variable. The below table
lists all the data types supported by Visual Basic 2010, along with the storage size
and range of values of these data types:
Table: Visual Basic 2010 Data Types
Data Type

Storage Size

Value Range

Boolean

Depends on the
implementing platform

True or False

Byte

1 byte

0 through 255

Char (single
Character)

2 bytes

0 through 65535

Date

8 bytes

0:00:00(midnight) on Jan
1,0001 through 11:59:59 PM
on December 31, 9999

Decimal

16 bytes

(+/-7.9E+28)
(+/-1E-28)

Double (double8 bytes


precision floatingpoint)

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

-1.79769313486231570E+308
through
4.94065645841246544E-324
for negative values;
4.94065645841246544E-324

through
1.79769313486231570E+308
for positive values.
Integer

4 bytes

-2,147,483,684 through
2,147,483,647.

Long (long
integer)

8 bytes

-9223,372,036,854,775,808
through
9223,372,036,854,775,807
(9.2E+18)

Object

4 bytes on 32-bit
platform

8 bytes on 64-bit platform


Any type can be stored in a
variable of type Object.

SByte

1 byte

-128 through 127

Short(short
integer)

2 byte

-32,768 through 32,767.

Single (single4 byte


precision floatingpoint)

-3,4028235E+38 through
-1.401298E-45 for negative
values;
1.401298E-45 through
3.4028235E+38 for positive
values;

String (variablelength)

Depends on
implementing platform

0 to approximately 2 billion
Unicode characters.

UInteger

4 bytes

0 through 4,294,967,295.

ULong

8 bytes

O through
18,446,744,073,709,551,615
(1.8E + 19).

UShort

2 bytes

0 through 65,535.

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

Variable Scope and life Time of a Variable:


Every variable in Visual Basic has a scope. The scope of the variables is the section
of application that can see and manipulate the variable. If a variable declared within
a procedure only the code in specific procedure has access to that variable. This
variable does not exist for the rest of application, when variables scope is limited to
a procedure it is called local.
For syntax:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles Button1.Click
Dim num1, num2, sum As Single
num1 = 100
num2 = 200
sum = num1 + num2
MsgBox(" The Sum of" & num1 & " and " & num2 & "is " &
sum)
End Sub
End Class
In some situations the entire application must access a certain variable in this case
the variable the must be declared as public. Public variable has a global scope, to
declare a public variable use public statement in place of dim statement,
moreover public variable may not appear inside procedures. They must be declared
as form variable or in a module.
For example:
Public A as integer.
Life of variable is limited to the execution of the body of the procedures or
functions in which they are declared. Thus each time the execution of the
procedures or functions body ends variable looses their values and are reinitialized
on the recall of the procedure or function. In order to retain the values of the
variables are declared as static. Static variables retain their previous values and
remain in memory till the execution of the program.
Data Type conversion:
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

While working with data type in visual Basic, sometimes you need to convert the
data type for a value stored in a variable to another data type. Converting one data
type to another type is known as data type conversion. Before performing data type
conversion between two data types, you must ensure that these data types are
compatible to one another.
Visual Basic 2010 provides a number of conversion function to perform data type
conversions. Given table lists data type conversion available in Visual Basic 2010,
along with their purpose.
Table: Data Type Conversion Functions in Visual
Basic 2010
Conversion
Function

Purpose

CBool

Converts an expression to the


Boolean data type.

CByte

Converts an expression the Byte


data type.

CChar

Converts an expression to the


Char data type

CDate

Converts an expression to the


Date data type

CDbl

Converts an expression to the


Double data type

CDec

Converts an expression to the


Decimal data type

CInt

Converts an expression to the


Integer data type

CLng

Converts an expression to the


Long data type

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

CObj

Converts an expression to the


Object data type

CShort

Converts an expression to the


Short data type

CSng

Converts an expression to the


Single data type

CStr

Converts an expression to the


String data type

CUInt

Converts an expression to the


UInteger data type

CULng

Converts an expression to the


ULong data type

CUShort

Converts an expression to the


UShort data type

Module Module1
Sub Main()
Dim dblData As Double
Dim intData As Integer
Dim boldata As Boolean
Dim lngdata As Long
dblData = 3.14159
intData = CInt(dblData)
boldata = CBool(intData)
lngdata = CLng(boldata)
Console.WriteLine("intData = " & Str(intData))
Console.WriteLine("bolData = " & Str(boldata))
Console.WriteLine("lngData = " & Str(lngdata))
Console.ReadLine()
End Sub
End Module
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

If you cannot remember the name of a particular conversion function, you can also
us the CType function, which allows you to specify a type you want to convert to.
Listing code shows the code for converting data types by using the CType function.
Module Module1
Sub Main()
Dim dblData As Double
Dim intData As Integer
dblData = 3.14159
intData = CType(dblData, Integer)
Console.WriteLine("intData = " & Str(intData))
Console.ReadLine()
End Sub
End Module
More often than not the CType function generates a compilation error if the
conversion between the data types of the provided parameter is not possible. Even
the lack of a compiler error does not guarantee a successful conversion. In case you
are not properly working. In such cases, in Visual Basic 2010 uses TryCast
function that works similar to the CType function. The only difference is that
instead of throwing an exception, it returns Nothing in the event of the failure.
Code for using the TryCast Function
Module Module1
Sub Main()
Dim dblData As Object
Dim strData As String
dblData = 3.14159
strData = TryCast(dblData, String)
If strData IsNot Nothing Then
Console.WriteLine("intData=" & Str(strData))
End If
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Console.WriteLine("Could not cast")


Console.ReadLine()
End Sub
End Module
Operators
An operator is a symbol that is used to perform an operation on one or more
expression, called operands. Examples of operations performed by using operators
are addition, subtraction, multiplication and division. Visual Basic 2010 provides
different types of operators, which are as follows:
1. Arithmetic Operators
2. Assignment Operators
3. Concatenation Operators
4. Comparison Operators
5. Logical and bitwise Operators
6. Miscellaneous Operators
1. Arithmetic Operators:
The operators used to perform arithmetic operations, such as subtraction,
multiplication, and division, are called arithmetic operators. Table 1.1 lists the
different arithmetic operators available in Visual Basic 2010.
Table 1.1 Arithmetic Operators in Visual Basic 2010
Operato
r

Operation

Description

Example

Result

Addition

Adds two numbers

5+5

10

Subtraction

Subtracts two numbers

10-5

Multiplication

Multiplies two numbers

8*4

32

Division

Divides two numbers

10/5

Integer

Divides two numbers

5\2

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

division

and provides the


quotient

Exponentiatio
n

Multiplies first number 2^3


to itself n times, where n
refers to its exponent

Mod

Modulus

Divide first number with


second, and provides the
remainder

7 mod 5

2. Assignment Operators:
An assignment operator is an operator that stores the result of an operation in
a variable on the left side of the operator. Table 1.2 lists the different
assignment operators available in Visual Basic 2010.
Table 1.2 Assignment Operators in Visual Basic 2010
Operator

Operation

=
Assign a value to a variable or property
(Assignment
)
^=

Exponentiation followed by assignment

*=

Multiplication followed by assignment

/=

Division followed by assignment

\=

Integer division followed by assignment

+=

Addition followed by assignment

-=

Subtraction followed by assignment

&=

Concatenation followed by assignment

<< =

Perform arithmetic left shift on value of

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

variable
>> =

Perform arithmetic right shift on value of


variable

eg:
a+=b or
a=a+b
3. Concatenation Operators:
The process of combining two text strings into one string is called
concatenation and the operators used to perform string concatenation are
called concatenation operators. Table 1.3 lists the different concatenation
operators available in Visual Basic 2010:
Table 1.3 Concatenation Operators in Visual Basic 2010
Operato Description
r

Example

Result

&

Concatenates two
strings

Dim str1 As String


str1="Visual Basic" &
"2010"

Visual Basic
2010

Concatenates two
strings

Dim str1 As String


str1="Visual Basic" +
"2010"

Visual Basic
2010

4. Comparison Operators:
Comparison operators are used to compare two expressions. You can use then
operators to compare numeric values, strings, and objects. A comparison
operation returns a Boolean value, either True or False, as a result. Table 1.4
lists the different comparison operators available in Visual Basic 2010:
Table 1.4 Comparison Operators in Visual Basic 2010
Operator

Description

= (Equal to)

Checks if the value of the first expression 20=20 True

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

Example

is equal to the value of the second


expression

24-30
False

< > (Not equal to)

Checks if the value of the first expression 20 < > 40


is not equal to the value of the second
True
80 < > 80
expression
False

< ( Less than)

Checks if the value of the first expression 20 < 25


is less than the value of the second
True
50 < 25
expression
False

> (Greater than)

Checks if the value of the first expression 20 >10


is greater than the value of the second
True
15 > 25
expression
False

< = (Less than or


equal to )

Checks if the value of the first expression 20 <= 25


is less than or equal to the value of the
True
50 < =25
second expression
False

>= (Greater than or


equal to)

Checks if the value of the first expression 20 >=10


is greater than or equal to the value of the True
15 >= 25
second expression
False

Is

True if two object references refer to the


same object

IsNot

Helps in comparing reference variables


of two objects

Like

Perform string pattern matching

5. Logical and Bitwise Operators:


Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Logical operators are those operator that are used with expressions and
produce a Boolean value. Visual Basic 2010 supports six logical operators:
Not, And, Or, Xor, AndAlso and OrElse. Table 1.5 lists the different logical
and bitwise operators available in Visual Basic 2010:
Table 1.5 Logical and Bitwise Operators in Visual Basic 2010
Operato
r

Description

Example

And

Perform an And operation (for logical


operations: True if both operands are
True, False otherwise, the same for bitby-bit operations where you treat 0 as
False and 1 as True

Dim X,Y As Boolean


X=21>14 And15>9
True
Y=12>26 And 24>8
False

Not

Reverses the logical value of its operand, Dim X,Y As Boolean


from True to False and False to True, for X= Not 5 > 3 False
Y= Not 2 > 7 True
bitwise operations, turns 0 into 1 and 1
into 0

Or

Perform an Or operation (for logical


operations: True if either operand is True,
False otherwise, the same for bit-by-bit
operations where you treat 0 as False and
1 as True

Dim X,Y As Boolean


X=20>30 Or 5>9
False
Y=16>12 Or 15>27
True

Xor

Performs the logical exclusion on two


Boolean expressions. If only one Boolean
expression evaluates to True, then the final
result after applying the Xor operation is
True.

Dim X,Y As Boolean


X= 28>14 Xor 5>9
True
Y= 25>29 Xor 14>15
False

AndAlso

Performs the logical conjunction of two


Boolean expressions. The differerence
between AndAlso and And operators is

Dim l As Integer =17


Dim m As Integer
=12

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

OrElse

that the AndAlso operator displays the


short-circuiting behavior, which means
that if the first expression in the AndAlso
expression evaluates to False, the second
expression is not evaluated as the value of
the second expression is evaluated based
on the first expression.

Dim n As Integer =10


Dim
Check,check1,Check
2 As Boolean
Check= l>m AndAlso
m>n T
Check1=m>l
AndAlso m>n F
Check2=l>m
AndAlso n>m F

Performs the short-circuiting logical


disjunction of two Boolean expressions.
This means that if the first condition in the
OrElse expression evaluates to True, then
the second condition is not evaluated and
the OrElse expression returns True.

Dim l As Integer =17


Dim m As Integer
=12
Dim n As Integer =10
Dim
Check,check1,Check
2 As Boolean
Check= l>m OrElse
m>n T
Check1=m>l OrElse
m>n T
Check2=m>l OrElse
n>m F

6. Miscellaneous Operators:
In addition to all operators discussed so far, some other operators are also used
in Visual Basic 2010, called miscellaneous operators. There are five
miscellaneous operators in Visual Basic 2010: AddressOf, GetType, TypeOf,
Function. Table 1.6 lists the different miscellaneous operators available in
Visual Basic 2010:
Table 1.6 Miscellaneous Operators in Visual Basic 2010
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Operator

Description

AddressOf

Gets the address of a procedure

GetType

Gets information about a type

Function
expression

Use to declare parameters and code

If

Return values based on certain


condition

TypeOf

Compare an object reference variable


to a data type

Array:
An array is a set of values that are logically related to each other, such as marks
obtained by the students of a class in a particular subject. It enables you to stores a
set of the same data type.
An array allows you to refer to these related values by the same name and to use a
number, called index, to identify individual values. The individual values of an
array are called the elements of the array. These elements are stored in the array
with the index values starting from 0 to one less than the size of the array.
Array Declaration:
An array, like any other variables, must be declared with the Dim statement
followed by the name of the array.
for example:
Dim Name(15)
Dim Salary(15)
Dim Names(10,20)
Optionally, you could specify the type of the array's elements with the As keyword:
Dim Name(15) As String
Dim Salary(15) As Long
Dim Names(10,20) As String
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Arrays can be of two types, which are as follows:


Standard Arrays
Dynamic Arrays
Standard Arrays:
Standard arrays are those arrays whose size cannot be changed at runtime. The Dim
statement is normally used to declare a standard array. Standard arrays are:
One Dimension Arrays:
An array whose elements are specified by a single subscript is known as a single
dimension array. This is the simplest form of an array.
Module Module1
Sub Main()
Dim counter As Integer = 0
Dim AuthorName As String() = New String(5) {}
AuthorName(0) = "Puneet"
AuthorName(1) = "Shambhu"
AuthorName(2) = "Bhola"
AuthorName(3) = "Yogendra"
AuthorName(4) = "Ramchandra"
Console.WriteLine("The Student names are:")
For counter = 0 To 4
Console.WriteLine(AuthorName(counter))
Next counter
Console.Write("press ENTER to exit...")
Console.ReadLine()
End Sub
End Module
Multidimensional Dimension Array:
Arrays having more than one dimension are called multidimensional arrays. It is
used for table processing or matrix manipulation.
eg: Dim mark(3,5)
Dim Board(10,10) As Integer

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

Dynamic Array:
Dynamic arrays are the arrays whose size varies at runtime. This type of array is
used to store a list of values that can be changed during the execution of program.
You can declare a dynamic array without specifying size in the parenthesis, by
using the Dim statement. To specify the size of the array at runtime, you need to use
the ReDim statement, as shown in the following code snipped:
ReDim [Preserve] varname (subscripts)
In the preceding syntax, the Preserve keyword is used to preserve the data an
existing array when you change the size of the last dimention. The varname
argument holds the name of the array to dimension again.
Consider the following code snippet,
Dim DynaArr( ) As String
ReDim DynaArr(10)
DynaArr(0)="String10"
'Need more data space !
ReDim DynaArr(100)
DynaArr(50)="String 50"
Module Module1
Sub Main()
Dim counter As Integer
Dim studentName() As String
ReDim studentName(3)
Console.WriteLine("Enter the Student Names")
For counter = 0 To 2
Console.Write("Student " & (counter + 1) & " : ")
studentName(counter) = Console.ReadLine()
Next counter
ReDim Preserve studentName(5)
For counter = 3 To 4
Console.Write("Student " & (counter + 1) & " : ")
studentName(counter) = Console.ReadLine()
Next counter
Console.WriteLine("The Student Names are:")
For counter = 0 To 4
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Console.WriteLine(studentName(counter))
Next counter
Console.Write("press ENTER to exit...")
Console.ReadLine()
End Sub
End Module
Enumeration
Enumerations or Enums are strongly typed constants. They are essentially unique
types that allow you to assign symbolic names to integral values. Enumerations can
be declared using the Enum keyword at the module, class, structure, procedure.
You can use enumerations to define a set of values that are logically related to each
other.
eg:
Module Module1
Enum Days
Sunday = 1
Monday = 2
Tuesday = 3
Wednesday = 4
Thursday = 5
Friday = 6
Saturday = 7
End Enum
Sub Main()
Console.WriteLine("Wednesday is day " & Days.Wednesday)
Console.ReadLine()
End Sub
End Module
Strings:
A string is a sequence of character. Strings are supported by the .NET String class
in Visual Basic. You declare a string in the following way:
Dim strvar As String
Similar to other types of variables, you can also initialize a string when you declare
it, as shown in the following code snippet:
Dim strvar As String = "Rapti Engineering College"
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Commonly used string handling functions and methods are given in the table.
Table: String Handling Functions and Methods in Visual Basic 2010
Functions & Methods

Operation

&,+, String.Concat, String.Join

Concatenate two strings

StrComp, String.Compare, String.Equals,


String.CompareTo

Compare two strings

StrConv, CStr, String.ToString

Convert string

=, String.Copy

Copying strings.

Format, Lcase, Ucase, String.Format,


String.ToUpper, String.ToLower

Convert to lowercase or upper

Str, Val.Format, String.Format

Convert to and from number

Space, String, String.String

Create string of a repeating


character

String.Split

Create an array of strings from one


string

Len, String.Length

Find length of string

Mid, String.SubString

Get a substring

String.Insert

Insert a substring

LSet,Rset,String.PadLeft, String.PadRight

Justify a string with padding

InStr, Left, LTrim, Mid, Right, RTrim, Trim,


Manipulate strings
String.Trim, String.TrimEnd, String.TremStart
Mid, String.Remove

Remove text

Mid,String.Replace

Replace text

Option Compare

Set string comparison rule

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

InStr, String.Chars, String.IndexOf,


String.IndexOf Any, String.LastIndexOf,
String.LastIndexOfAny

Search Strings

LTrim, RTrim, Trim, String.Trim,


String.TrimEnd, String.TrimStart

Trim leading or trailing spaces

Asc, AscW, Chr

Work with character codes

String
eg:
Imports System.Console
Imports Stg = Microsoft.VisualBasic.Strings
Module Module1
Sub Main()
MsgBox(Stg.Right("Hello World", 5))
ReadLine()
End Sub
End Module
This example uses the UCase, LCase, Len,Trim and Mid functions.
Module Module1
Sub Main()
Dim strText1 As String = "rapti engineeing college"
Dim strText2, strText3, strText4, strText5 As String
Dim strText6, strText7 As String
strText2 = UCase(strText1) 'change in uppercase
strText3 = strText1.ToUpper 'change in uppercase
strText4 = strText2.ToLower 'change in lowercase
strText5 = LCase(strText2) 'change in lowercase
strText6 = Len(strText1) 'finding length of strings
strText7 = strText1.Length 'finding length of strings
' Initializes string.
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Dim TestString As String = " <-Trim-> "


Dim TrimString, TrimString1, TrimString2, TrimString3 As
String
' Returns "<-Trim-> ".
TrimString = LTrim(TestString)
' Returns " <-Trim->".
TrimString1 = RTrim(TestString)
' Returns "<-Trim->".
TrimString2 = LTrim(RTrim(TestString))
' Using the Trim function alone achieves the same result.
' Returns "<-Trim->".
' Creates text string.
Dim ts As String = "Mid Function Demo"
' Returns "Mid".
Dim FirstWord As String = Mid(ts, 1, 3)
' Returns "Demo".
Dim LastWord As String = Mid(ts, 14, 4)
' Returns "Function Demo".
Dim MidWords As String = Mid(ts, 5)
Dim mw As String = ts.Substring(5, 4)
TrimString3 = Trim(TestString)
Console.WriteLine(strText2)
Console.WriteLine(strText3)
Console.WriteLine(strText4)
Console.WriteLine(strText5)
Console.WriteLine(strText6)
Console.WriteLine(strText7)
Console.WriteLine(TrimString)
Console.WriteLine(TrimString1)
Console.WriteLine(TrimString2)
Console.WriteLine(TrimString3)
Console.WriteLine(FirstWord)
Console.WriteLine(LastWord)
Console.WriteLine(MidWords)
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Console.WriteLine(nw)
Console.ReadLine()
End Sub
End Module
Example 2:
Module Module1
Sub Main()
Dim TestDateTime As Date = #1/27/2001 5:04:23 PM#
Dim TestStr As String
' Returns current system time in the system-defined long time
format.
TestStr = Format(Now(), "Long Time")
Console.WriteLine(TestStr)
' Returns current system date in the system-defined long date
format.
Dim TestStr1 = Format(Now(), "Long Date")
Console.WriteLine(TestStr1)
' Also returns current system date in the system-defined long
date
' format, using the single letter code for the format.
Dim TestStr2 = Format(Now(), "D")
Console.WriteLine(TestStr2)
' Returns the value of TestDateTime in user-defined date/time
formats.
' Returns "5:4:23".
Dim TestStr3 = Format(TestDateTime, "h:m:s")
Console.WriteLine(TestStr3)
' Returns "05:04:23 PM".
Dim TestStr4 = Format(TestDateTime, "hh:mm:ss tt")
Console.WriteLine(TestStr4)
' Returns "Saturday, Jan 27 2001".
Dim TestStr5 = Format(TestDateTime, "dddd, MMM d yyyy")
Console.WriteLine(TestStr5)
' Returns "17:04:23".
Dim TestStr6 = Format(TestDateTime, "HH:mm:ss")
Navin Malla Birendranagar 11 Airport Surkhet
E-Mail:[email protected]

Console.WriteLine(TestStr6)
' Returns "23".
Dim TestStr7 = Format(23)
Console.WriteLine(TestStr7)
' User-defined numeric formats.
' Returns "5,459.40".
Dim TestStr8 = Format(5459.4, "##,##0.00")
Console.WriteLine(TestStr8)
' Returns "334.90".
Dim TestStr9 = Format(334.9, "###0.00")
Console.WriteLine(TestStr9)
' Returns "500.00%".
Dim TestStr10 = Format(5, "0.00%")
Console.WriteLine(TestStr10)
Console.ReadLine()
End Sub
End Module

Navin Malla Birendranagar 11 Airport Surkhet


E-Mail:[email protected]

You might also like