0% found this document useful (0 votes)
8 views6 pages

CSC 201 Week 7 Working With String

This document provides an overview of working with strings and conversions in Visual Basic. It covers string declaration, concatenation, length, substring extraction, case conversion, text replacement, and various conversion methods including implicit and explicit conversions, built-in functions, and the Convert class. Additionally, it discusses handling null values and converting between dates and strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

CSC 201 Week 7 Working With String

This document provides an overview of working with strings and conversions in Visual Basic. It covers string declaration, concatenation, length, substring extraction, case conversion, text replacement, and various conversion methods including implicit and explicit conversions, built-in functions, and the Convert class. Additionally, it discusses handling null values and converting between dates and strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Lecture Note 7

Working with Strings in Visual Basic

1. Declaring and Initializing Strings

Strings can be declared and initialized as follows:

Dim greeting As String = "Hello, World!"

2. Concatenation

You can join strings using the & or + operators.

Dim firstName As String = "John"


Dim lastName As String = "Metose"
Dim fullName As String = firstName & " " & lastName
Console.WriteLine(fullName)

3. String Length

You can find the length of a string using the Length property.

Dim message As String = "LASUED is my school"


Dim length As Integer = message.Length
Console.WriteLine"The length is: " & length) ' Output: 12

Explanation:

 Length gets the number of characters in the current string, including spaces.

4. Substring

The Substring method extracts a portion of a string.

Dim sentence As String = "Visual Basic Programming"


Dim subPart As String = sentence.Substring(7, 10)
Console.WriteLine(subPart)
Explanation:

 Substring(startIndex, length) extracts a portion of the string starting at


startIndex (0-based) and retrieves the specified length.

5. Converting Case

Convert a string to uppercase or lowercase using ToUpper and ToLower.

Dim input As String = "Hello"


Console.WriteLine(input.ToUpper()) ' Output: HELLO
Console.WriteLine(input.ToLower()) ' Output: hello

Explanation:

 ToUpper converts the entire string to uppercase.


 ToLower converts the entire string to lowercase.

6. Replacing Text

Replace a substring with another string using the Replace method.

Dim sentence As String = "I love programming."


Dim newSentence As String = sentence.Replace("love", "enjoy")
Console.WriteLine(updatedSentence) ' Output: I enjoy programming.

Explanation:

 Replace(oldValue, newValue) substitutes oldValue with newValue.

Conversions in Visual Basic

In Visual Basic (VB.NET), conversions involve changing a value from one data type to another.
VB.NET provides various techniques for type conversion, including implicit and explicit
conversions, built-in conversion functions, and helper classes like Convert. Here's an overview:

Summary Table of Conversion Methods

Method Purpose

CInt Converts to Integer


CStr Converts to String
CDbl Converts to Double
CDec Converts to Decimal
Convert Versatile class for multiple conversions
.Parse Converts strings to numbers, throws error
.TryParse Safe conversion, avoids exceptions
.ToString Converts any value to a string

1. Implicit Conversion

Implicit conversions happen automatically when no data loss or error can occur during the
conversion.

Example:
Dim intValue As Integer = 100
Dim dblValue As Double = intValue ' Implicit conversion from Integer to
Double
Console.WriteLine(dblValue) ' Output: 100.0

Explanation:

 VB.NET automatically converts intValue (Integer) to dblValue (Double) without needing


explicit code because the conversion is safe.

2. Explicit Conversion

Explicit conversions require you to specify the conversion using functions or casting when there
is a risk of data loss.

Example:
Dim dblValue As Double = 123.45
Dim intValue As Integer = CType(dblValue, Integer) ' Explicit conversion
using CType
Console.WriteLine(intValue) ' Output: 123

Explanation:

 CType(expression, type) explicitly converts dblValue (Double) to intValue (Integer).


The fractional part is truncated during the conversion.

3. Conversion Functions

VB.NET provides built-in functions like CInt, CStr, CDbl, etc., for specific conversions.
Common Conversion Functions:

 CInt: Converts to Integer.


 CStr: Converts to String.
 CDbl: Converts to Double.
 CDec: Converts to Decimal.

Example:
Dim strValue As String = "50"
Dim intValue As Integer = CInt(strValue)
Console.WriteLine(intValue + 10) ' Output: 60

Explanation:

 CInt converts strValue (String) to an Integer for arithmetic operations.

4. Using Convert Class

The Convert class offers more flexible and robust conversion methods.

Example:
Dim strValue As String = "123.45"
Dim dblValue As Double = Convert.ToDouble(strValue)
Console.WriteLine(dblValue + 10.5) ' Output: 133.95

Explanation:

 Convert.ToDouble parses the string and converts it to a Double.

5. Parsing Strings to Numbers

The .Parse and .TryParse methods are commonly used to convert strings to numeric types
safely.

Example with .Parse:


Dim strValue As String = "200"
Dim intValue As Integer = Integer.Parse(strValue)
Console.WriteLine(intValue * 2) ' Output: 400

Example with .TryParse:


Dim strValue As String = "300a" ' Invalid input
Dim intValue As Integer
If Integer.TryParse(strValue, intValue) Then
Console.WriteLine(intValue)
Else
Console.WriteLine("Conversion failed!") ' Output: Conversion failed!
End If

Explanation:

 .Parse throws an exception if the string is invalid.


 .TryParse avoids exceptions and instead returns True or False depending on the success of
the conversion.

6. Numeric to String Conversion

To convert numbers to strings, use the ToString method or CStr.

Example:
Dim number As Integer = 42
Dim strValue As String = number.ToString()
Console.WriteLine("The answer is " & strValue) ' Output: The answer is 42

7. Widening and Narrowing Conversions

 Widening Conversion: Converts from a smaller type to a larger type (no data loss).
 Narrowing Conversion: Converts from a larger type to a smaller type (possible data loss).

Widening Example:
Dim intValue As Integer = 100
Dim dblValue As Double = intValue ' Widening, no data loss

Narrowing Example:
Dim dblValue As Double = 123.456
Dim intValue As Integer = CType(dblValue, Integer) ' Narrowing, fractional
part lost
Console.WriteLine(intValue) ' Output: 123

8. Handling Null and Empty Values

Handle null or empty values carefully during conversion to avoid runtime errors.

Example:
Dim strValue As String = Nothing
Dim intValue As Integer = If(String.IsNullOrEmpty(strValue), 0,
CInt(strValue))
Console.WriteLine(intValue) ' Output: 0

Explanation:

 Use String.IsNullOrEmpty to check for null or empty strings before conversion.

9. Converting Between Date and String

VB.NET supports converting dates to strings and vice versa.

Example:
Dim currentDate As Date = Date.Now
Dim strDate As String = currentDate.ToString("yyyy-MM-dd")
Console.WriteLine(strDate) ' Output: 2025-01-11

Dim parsedDate As Date = Date.Parse(strDate)


Console.WriteLine(parsedDate) ' Output: 1/11/2025 12:00:00 AM

Note: Use DirectCast for conversions within inheritance hierarchies.

You might also like