Strings
Strings
Ms.Nausheeda B S
1
Introduction
• Strings represent a sequence of characters
• Easiest way – using character array
char [] cArray = new char[4];
cArray[0]=‘N’;
cArray[1]=‘a’;
cArray[2]=‘m’;
cArray[3]=‘e’;
2
• C# supports two types of strings
• Immutable
• Mutable
3
Creating Strings
• Predefined reference type – string
• When we declare a string using string type, we
are in fact declaring the object to be of type
System.String
– Assigning string literals
– Copying from one object to another
– Concatenating two objects
– Reading from keyboard
– Using ToString method
4
Assigning string literals
String s1 ;
S1 =“abc”;
Or
String s1 = “abc”;
5
Copying strings
• Using overloaded = operator
• Using static Copy method
String s2 = s1;
String s2 = string.Copy(s1);
6
Concatenating strings
• Using overloaded + operator
• Using static Concat method
String s3 = s1 + s2;
String s3 = string.Concat(s1, s2);
7
• Reading from keyboard
• String s = Console.ReadLine();
8
Verbatim strings
• Strings beginning with @ symbol
String s1 = @”\EBG\Csharp\string.cs”
9
String Methods
• String objects are immutable
• Cannot modify the characters contained in
them
• Has many built-in operations
10
String class methods
• Inserting
11
Comparing Strings
• Overloaded Compare()
• Overloaded Equals()
• Overloaded == operator
12
• Compare ()
Int n = string.Compare(s1, s2)
Returns 0 if s1 = s2
Returns 1 if s1 < s2
Return -1 if s1 > s2
14
• == operator
Bool b3 = (s1 == s2);
15
Finding substrings
s.Substring(n);
s.Substring(n1, n2);
16
Mutable Strings
• Mutable strings that are modifiable are created using
the StringBuilder class
• Also called as dynamic strings
• Can grow dynamically as more characters are added
to them
• Unbound or max value
19