CSC 201 Week 7 Working With String
CSC 201 Week 7 Working With String
2. Concatenation
3. String Length
You can find the length of a string using the Length property.
Explanation:
Length gets the number of characters in the current string, including spaces.
4. Substring
5. Converting Case
Explanation:
6. Replacing Text
Explanation:
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:
Method Purpose
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:
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:
3. Conversion Functions
VB.NET provides built-in functions like CInt, CStr, CDbl, etc., for specific conversions.
Common Conversion Functions:
Example:
Dim strValue As String = "50"
Dim intValue As Integer = CInt(strValue)
Console.WriteLine(intValue + 10) ' Output: 60
Explanation:
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:
The .Parse and .TryParse methods are commonly used to convert strings to numeric types
safely.
Explanation:
Example:
Dim number As Integer = 42
Dim strValue As String = number.ToString()
Console.WriteLine("The answer is " & strValue) ' Output: The answer is 42
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
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:
Example:
Dim currentDate As Date = Date.Now
Dim strDate As String = currentDate.ToString("yyyy-MM-dd")
Console.WriteLine(strDate) ' Output: 2025-01-11