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

Lecturer 3 String Methods

The document discusses how to obtain user input in C# using the ReadLine method and addresses potential null value issues introduced in C# 8.0 with nullable reference types. It provides solutions for handling null values, including using nullable strings, the null-coalescing operator, and explicit null checks. Additionally, it covers string formatting methods such as concatenation, String.Format, and string interpolation, along with various string functions available in C#.

Uploaded by

click.wasiq
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 views29 pages

Lecturer 3 String Methods

The document discusses how to obtain user input in C# using the ReadLine method and addresses potential null value issues introduced in C# 8.0 with nullable reference types. It provides solutions for handling null values, including using nullable strings, the null-coalescing operator, and explicit null checks. Additionally, it covers string formatting methods such as concatenation, String.Format, and string interpolation, along with various string functions available in C#.

Uploaded by

click.wasiq
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

Visual Programming Lecture 3

Farman Ullah
Text input from the user

We can get text input from the user using the ReadLine method.
This method waits for the user to type some text. Then, as soon as
the user presses Enter, whatever the user has typed is returned as a
string value.
string name= Console .ReadLine ();
Warning Message: Converting null literal or possible null value to non-nullable type.

Reason for the Error:


❖ In C# 8.0 and later, nullable reference types are introduced.
❖ [Link]() returns a string? (nullable string), meaning it can
return a null value if the input is empty or interrupted.
❖ Assigning a nullable string (string?) to a non-nullable string (string name)
triggers this warning or error.
Solutions:
Solution 1: Use a Nullable String (string?)
Modify the declaration of name to explicitly allow null values:
string ? name = Console .ReadLine (); // Allow null values
This resolves the issue because name is now a nullable string (string?),
matching the return type of [Link]().

Solution 2: Use the Null-Coalescing Operator (??)


If you want to ensure name never holds null, use the null-coalescing
operator (??) to provide a default value:
string name = Console .ReadLine () ?? "Default Name" ;

If [Link]() returns null, "Default Name" is assigned instead.


Solution 4: Use Explicit Null Handling
You can also manually check for null before using name:

string ? input = Console .ReadLine ();


while (input == null )
{
Console .WriteLine ( "Input was null, Try Again: " );
input = Console .ReadLine ();
}
Console .WriteLine (input);

If the user presses the Enter key without typing anything, [Link]() returns an
empty string (""), not null.
However, if the input stream is closed or redirected and no input is provided,
[Link]() can return null. But under normal circumstances in a console
application, it will return an empty string when the user simply presses Enter.

User just presses Enter without typing anything:

Input is an empty string.

In most cases, an empty input means "" (not null).


In C#, [Link]() will return null in the following scenarios:

1. End of Input Stream (EOF)


❑ If the standard input (stdin) is closed or redirected and reaches the end of
the input stream, [Link]() will return null.
❑ This can happen when reading from a file or a pipe that has no more data.

If [Link] is empty, [Link]() may return null when the end of the
file is reached.
2. When Using Ctrl + Z (Windows) or Ctrl + D (Linux/macOS)

❑ f the user presses Ctrl + Z on Windows or Ctrl + D on Linux/macOS in the


console, it signals EOF (End of File), making [Link]() return null.
3. When [Link]() is Used with a StringReader

❑ f the user presses Ctrl + Z on Windows or Ctrl + D on Linux/macOS in the


console, it signals EOF (End of File), making [Link]() return null.

using System;
using [Link];

class Program
{
static void Main()
{
StringReader sr = new StringReader ( "" ); // Empty input
Console .SetIn ( sr );

string ? input = Console .ReadLine ();


Console .WriteLine (input == null ? "Input is null" : "Input is: "
+ input);
}
}
String Formatting

❑ String Concatenation:

❑ [Link] Method

❑ String Interpolation
String Concatenation:
The + operator can be used between strings to combine them. This is called
concatenation:

string firstName = "John ";


string lastName = "Doe";
string name = firstName + lastName;
[Link](name);

You can also use the [Link]() method to concatenate two strings

string firstName = "John ";


string lastName = "Doe";
string name = [Link](firstName, lastName);
[Link](name);
[Link] Method
[Link] allows you to create a formatted string by specifying
placeholders for values and then providing those values as arguments. The
placeholders are represented by curly braces {} with optional format
specifiers. Here's an example:

string msg = [Link]("Hello, {0}! Your age is {1:D2}.", "John", 25);

In this example, {0} and {1:D2} are placeholders for the first and second
arguments, respectively. {1:D2} is a format specifier that ensures the second
argument is displayed as a two-digit decimal.
1. Numeric Format Specifiers
These are used to format numbers in different ways.

Format
Description Example Output
Specifier

C (Currency) Formats as currency [Link]("{0:C}", 1234.567) $1,234.57

D (Decimal) Integer digits, with leading zeros if specified [Link]("{0:D6}", 1234) 1234

E (Exponential) Scientific notation [Link]("{0:E2}", 1234.567) 1.23E+03

F (Fixed-point) Fixed decimal places [Link]("{0:F2}", 1234.567) 1234.57

G (General) Compact format, either fixed-point or scientific [Link]("{0:G}", 1234.567) 1234.567

N (Number) Includes group separators [Link]("{0:N2}", 1234.567) 1,234.57

P (Percent) Multiplies by 100 and adds % [Link]("{0:P}", 0.1234) 12.34%

X (Hexadecimal) Converts integer to hex [Link]("{0:X}", 255) FF


2. Date and Time Format Specifiers
These are used to format DateTime values.

Example
Format Specifier Description (DateTime(2025, 3, 8, Output
14, 30, 45))
d (Short Date) Short date pattern [Link]("{0:d}", dt) 3/8/2025
D (Long Date) Long date pattern [Link]("{0:D}", dt) Saturday, March 8, 2025
t (Short Time) Short time pattern [Link]("{0:t}", dt) 2:30 PM
T (Long Time) Long time pattern [Link]("{0:T}", dt) 2:30:45 PM
Saturday, March 8, 2025 2:30
f (Full Date/Short Time) Combination of D and t [Link]("{0:f}", dt)
PM
Saturday, March 8, 2025
F (Full Date/Long Time) Combination of D and T [Link]("{0:F}", dt)
2:30:45 PM
M or m (Month/Day) Month and day only [Link]("{0:M}", dt) 8-Mar

Y or y (Year/Month) Year and month only [Link]("{0:Y}", dt) Mar-25


2025-03-
o (Round-trip) ISO 8601 format [Link]("{0:o}", dt)
08T14:30:45.0000000
Sat, 08 Mar 2025 14:30:45
R (RFC1123) Internet standard format [Link]("{0:R}", dt)
GMT
3. Custom Formatting
You can also use custom format strings.

Numeric Example
[Link]("{0:00000}", 42); // Output: "00042"

DateTime Example
Console .WriteLine ( String .Format ( "{0:yyyy - MM
- dd HH:mm:ss }" , DateTime .Now ));
// Output: "2025-03-08 13:40:49 "

Console .WriteLine ( String .Format ( "{0:yyyy - MM


- dd hh:mm:ss tt }" , DateTime .Now ));

// Output: "2025-03-08 01:40:49 PM"

Console .WriteLine ( String .Format ( "{0:yy - MM


- dd HH:mm:ss }" , DateTime .Now ));
// Output: "25-03-08 13:40:49 "
String Interpolation
String interpolation allows you to embed expressions within string literals using
the $ symbol and curly braces {}. This method is available in C# 6.0 and later:

Structure of an interpolated string

{<interpolationExpression>[,<alignment>][:<formatString>]}

string name = "John";


int age = 25;
string interpolatedString = $"Hello, {name}! Your age is {age:D2}.";
String Interpolation
Structure of an interpolated string

{<interpolationExpression>[,<alignment>][:<formatString>]}

Element Description
interpolationExpression The expression to be formatted. If null, it outputs
an empty string ([Link]).
alignment Defines the minimum width of the formatted
output. Positive values right-align, negative
values left-align.
formatString A format string applicable to the expression's type.
Display Currency in Local Format

static void Main( string [] args )


{

double x = 11 . 5;

// Create a CultureInfo object for Pakistan


CultureInfo pakistanCulture = new CultureInfo ( " ur - PK" ) ;

// Format the number as PKR currency with 4 decimal places


Console . WriteLine ( String . Format ( pakistanCulture , "{ 0: C2}" , x)) ;
// String interpolation Method
Console . WriteLine ( $" { x . ToString ( "C 2" , pakistanCulture )} " ) ;
}
Alignment

Console .WriteLine ( $" { Math .PI,20: F3 } –Hello World" );

Console .WriteLine ( $" { Math .PI, - 20: F3 } –Hello World" );


String Functions in C#
Method Definitions
Basic String Methods
It is a string property that returns length of string.
Length string str = "Hello" ;
Console .WriteLine([Link]); // Output: 5
Converts a string to uppercase or lowercase.
ToUpper()/ string str = "Hello" ;
ToLower() Console .WriteLine([Link]()); // Output: HELLO
Console .WriteLine([Link]()); // Output: hello
Removes white spaces or specified characters from the beginning
Trim()/
and/or end.
TrimStart()/
TrimEnd()
string str = " Hello " ;
Console .WriteLine ( [Link] ()); // Output: "Hello"
String Functions in C#
Method Definitions
Substring and Searching Methods
This method returns substring.
Substring(int
startIndex,int length)
string str = "Hello World" ;
Console .WriteLine ( [Link] (0, 5)); // Output: Hello
The Substring(int startIndex) method extracts a portion of a string,
Substring(int
startIndex)
starting from the specified index to the end of the string.
string result = [Link](startIndex);
Returns the index of the first/last occurrence of a substring.
IndexOf( string value) /
string str = "Hello World" ;
LastIndexOf(string
value)
Console .WriteLine ( [Link] ( "o" )); // Output: 4
Console .WriteLine ( [Link] ( "o" )); // Output: 7
Checks if a string contains a specific substring.
string str = "Hello World" ;
Contains(string value)
Console .WriteLine([Link]( "World" )); // Output:
True
Checks if a string starts or ends with a specific substring.
StartsWith(string value) / string str = "Hello World" ;
EndsWith(string value) Console .WriteLine ( [Link] ( "Hello" )); // Output: True
String Functions in C#
Method Definitions
String Modification Methods
Replaces occurrences of a substring.
string str = "Hello World" ;
Replace(oldStr, newStr)
Console .WriteLine ( [Link] ( "World" , "C#" ));
// Output: Hello C#
Removes a part of a string.
Remove(int startIndex,
int length)
string str = "Hello World" ;
Console .WriteLine ( [Link] (5, 6)); // Output: Hello
Removes all characters from the specified index to the end of the
Remove(int string.
startIndex) string str = "Hello World" ;
string removed = [Link] (5); // Returns "Hello"
Inserts a substring at a specified index.
Insert(int index, string string str = "Hello World" ;
value) Console .WriteLine ( [Link] ( "World" )); // Output:
True
String Functions in C#
Method Definitions
Splitting and Joining
Splits a string into an array of substrings.
string str = " apple,banana,grape ";
Split(char separator)
string [] fruits = [Link] ( ',’ );
Console .WriteLine (fruits[1]); // Output: banana
Joins an array of strings into a single string.
Join(string separator, string [] words = { "Hello" , "World" };
string[] values) string result = string .Join ( " " , words);
Console .WriteLine (result); // Output: Hello World
String Functions in C#
Method Definitions
Other Functions
Compares two strings.
string str1 = "Hello" ;
Equals(string value) string str2 = "hello" ;
Console .WriteLine ([Link](str2,
StringComparison .OrdinalIgnoreCase )); // Output: True
Checks if a string is null or empty/whitespace.
IsNullOrEmpty(string string str = "" ;
value)/ Console .WriteLine ( string .IsNullOrEmpty (str));
IsNullOrWhiteSpace(st // Output: False
ring value) Console .WriteLine ( string .IsNullOrWhiteSpace (str));
// Output: True
Pads a string with spaces.
PadLeft(int totalWidth)/ string str = "Hello" ;
PadRight(int totalWidth) Console .WriteLine ( [Link] (10)); // Output: " Hello"
Console .WriteLine ( [Link] (10)); // Output: "Hello "
String Functions in C#
Method Definitions
Other Functions
Formats a string using placeholders
string name = "John" ;
Format(string format,
object[] args)
int age = 25;
string result = string .Format ( "Name: {0}, Age: {1}" , name, age);
Console .WriteLine (result); // Output: Name: John, Age: 25
Converts the string to a character array.
string str = "Hello" ;
ToCharArray()
char [] chars = [Link] ();
// Returns ['H', 'e', 'l', 'l', 'o']
Concatenates two strings.
string str1 = "Hello" ;
Concat(string str1, string
str2)
string str2 = "World" ;
string result = string .Concat (str1, str2);
// Returns "HelloWorld"
String Functions in C#
Method Definitions
Other Functions
The [Link]() method is used to compare two strings
lexicographically (alphabetically or based on their Unicode values). It
returns an integer indicating their relative order. (Static Method)

int result
= string . Compare (A, B) ;
OR
int result = string .Compare (A, B,
[Link](s StringComparison .OrdinalIgnoreCase );
tring strA, string
strB) Return Values
The Compare() method returns an integer that indicates the relationship
between A and B:
Return Value Meaning
0 A and B are equal.
<0 A comes before B (A is smaller).
>0 A comes after B (A is larger).
String Functions in C#
Method Definitions
Other Functions

An instance method that compares two strings. (Instance Method)


Returns: Same int value as Compare().
Limited: No StringComparison parameter (always case-sensitive and
culture-aware).
CompareTo(string
strA, string strB)
string A = "apple" ;
string B = "banana" ;
int result = [Link] (B);
Console .WriteLine (result);
// Output: - 1 (Apple comes before Banana)

Feature [Link](A, B) [Link](B)


Method Type Static Instance
Parameters Two strings (A, B) One string (B)
StringComparison Support? ✅ Yes (e.g., case-insensitive) ❌ No
Use Case When flexibility is needed Simple comparisons
[Link]() (Deprecated in .NET Core)

string str1 = "Hello" ;


string str2 = string .Copy (str1);
Console .WriteLine (str2); // Output: "Hello"
GetType()
Definition: Returns the Type of the object.
Returns: A Type object representing the runtime type of the instance.
Use Case: Used in reflection to get metadata about an object.

string str = "Hello" ;


Type type = [Link] ();

Console .WriteLine (type); // Output: [Link]

You might also like