Vous êtes sur la page 1sur 19

Strings in C#

Bibek Kumar
CSE Deptt. DITU
bibek.kumar@dituniversity.edu.in

Mr.Bibek Kumar-Assistant Professor-CSE


INDEX
• Introduction.
• Immutable vs Mutable strings.
• String methods in C#.
• Comparing Strings
• Mutable strings.
• Regular Expressions.
• Method Parameter.

Mr.Bibek Kumar-Assistant Professor-CSE


Strings in C#
 Strings represents a group of characters and character array is a easiest way to
represent a sequence of characters in C#.
 Ex. char [ ] name= new char[4];
name[0]=‘N’; name[1]=‘a’; name[2]=‘m’; name[3]=‘e’;
 C# supports a feature known as regular expressions that can be used for complex string
manipulation and pattern matching.
 C# support a predefined reference type known as string.
 string can be use to declare string type objects of type
System.String class.
 System.Text and System.Text.RegularExpression namespaces
are also used in Building Strings,Formatting Expressions and
Regular Expression

Mr.Bibek Kumar-Assistant Professor-CSE


Immutable vs mutable strings
• Immutable string cannot be • mutable string can be changed or modify
changed once declared and once declared and defined.
defined. class mutableString
class ImmutableString {
{ static void Main(string[] args)
static void Main(string[] args) {
{ StringBuilder str = new StringBuilder(“DIT");
string str=“DIT”;
str.Append(“University");
str = str + “University”;
str.Append(“Dehradun");
Console.Writeline(str);
Console.WriteLine(str);
}
Note*: if we assign a string to str, another }
memory will be created and string will be Note*: if we assign a string to str, after append
written and GC Will collect earlier one. ing our string the same memory location will a
ppend the string.

Mr.Bibek Kumar-Assistant Professor-CSE


Immutable String Methods
Some predefined methods
Used in System.String class.

Mr.Bibek Kumar-Assistant Professor-CSE


Comparing Strings
Compare() Method
int n=string.Compare(s1,s2);
 Zero interger, if s1 is equal to s2
 A positive Integer (1) , if s1 is greater than s2
 A negative integer(-1), if s1 is less than s2

Equals() Method
There are two versions of Equals method. They are implemented as follows:-
bool b1= s2.Equals(s1);
bool b2= string.Equals(s2,s1);
These methods returns a Boolean value true if s1 and s2 are equal, otherwise false.

The == Operator
bool b3= (s1==s2); //b3 is true if they are equal
We very often use such statements in decision statements, like:-
if(s1==s2)

Mr.Bibek Kumar-Assistant Professor-CSE


Mutable Strings
 This type of strings are modifiable using the StringBuilder class.
StringBuilder str1=new StringBuilder(“hello”);
StringBuilder str2=new StringBuilder();
 They can grow dynamically as more characters are added to them.
 They can grow either unbounded or up to a configurable maximum.
 Mutable Strings are also known as dynamic strings.

Mr.Bibek Kumar-Assistant Professor-CSE


Mutable Strings (Contd…)
 The System.Text namespace contains the class StringBuilder,
therefore we must include the using System.Text directive for
creating and manipulating mutable strings.

Mr.Bibek Kumar-Assistant Professor-CSE


Mutable String Program
using System; //4.Inserting a String
using System.Text; s2.Insert(3,"Life");
class strbuild //5.Remove
s1.Remove(5,3);
{ public static void Main() //6.Replace
{ string str1,str2; s2.Replace('A', '*');
Console.WriteLine("Enter first string"); //7.Capacity
str1=Console.ReadLine(); int y= s1.Capacity;
Console.WriteLine("Enter Second string"); Console.WriteLine("Capacity is"+y);
s1.Capacity=100;
str2=Console.ReadLine(); y=s1.Capacity;
StringBuilder s1 = new StringBuilder(str1); Console.WriteLine("New Capacity is"+y);
StringBuilder s2 = new StringBuilder(str2); //8.Length
//1.Appending a String int z = s1.Length;
s1.Append("Smile"); int v = s2.Length;
Console.WriteLine(" Length of s1 "+ z);
// Console.WriteLine("String After Append :" +s1); Console.WriteLine("Length of s2"+ v);
//2.Append Format //9.MaxCapacity
s2.AppendFormat("1)s2 after Append Format {0}",s2); int c= s1.MaxCapacity;
s1.AppendFormat("2)s1 after Append Format {0}",s1); Console.WriteLine("Max Capacity"+s1);
//3.Ensure Capacity //10.setting a character
int n=s2.Length;
int x=s1.EnsureCapacity(30); s2[n-1]='@'; } }
Mr.Bibek Kumar-Assistant Professor-CSE
Regular Expression
Regular expression provide a powerful tool for searching
and manipulating a large text . A R.E. may be applied to a
text to complete tasks such as:
 To locate substrings and return them.
 To modify one or more substrings and return them.
 To Identify substrings that begins with or end with a
pattern of characters .
 To find all words that begins with a group of characters
and end with some other characters.
 To find all the occurrences of a substring pattern and
many more.

Mr.Bibek Kumar-Assistant Professor-CSE


Regular Expression (contd…)
Regular expression (also known as pattern string) is a string containing two types of
characters
1. Literals : characters that we wish to search and match in the text.
2. Metacharacters: Metacharacters are special characters that give command to the
regular expression parser.

\b , \B, \S* and | are metacharacters and m, er ,X, space and comma are Literals.

Mr.Bibek Kumar-Assistant Professor-CSE


Method Parameters
 Methods are declared inside the body of class.
modifier type methodname(formal parameter list) Example.
{ int product(int x, int y)
method body {
} Int m=x*y;
Return(m);
}

 C# employs four kinds of parameter.


1. Value Parameters
2. Output Parameters
3. Reference Parameters
4. Parameter arrays

Mr.Bibek Kumar-Assistant Professor-CSE


Pass by Value
- By default method parameters are passed by value.
- A parameter declare with no modifier is passed by value and called a value parameter.

using System;
class PassByValue
{
static void Change(int m)
{
m=m+10; //Value of m is changed.
}
public static void Main()
{
int x=100;
Change(x);
Console.WriteLine("x="+x);
}
}

Mr.Bibek Kumar-Assistant Professor-CSE


Pass by Reference
 A parameter declared with ref keyword is a reference parameter.
Example:-
void Modify(ref int x) //x is declared as reference parameter
 Unlike a value parameter, a reference parameter doesn’t create a new storage location.
 When a formal parameter is declared as ref , the corresponding arguments in the
method invocation must also be declared as ref.
Example:-
void Modify( ref int x)
{
x+=10; //value of m will be changed
}

int m= 5; //,m is initialized


Modify(ref m); //pass by reference

Mr.Bibek Kumar-Assistant Professor-CSE


Pass by Reference
using System;
class XYZ Console.WriteLine("m = "+m);
{ Console.WriteLine("n = "+n);
static void Swap(ref int x, ref int y) Swap(ref m, ref n);
{ Console.WriteLine("After Swapping:");
int temp=x; Console.WriteLine("m = "+m);
x=y; Console.WriteLine("n = "+n);
}
y=temp;
}
}
public static void Main()
{
int m=100;
int n=200;
Console.WriteLine("Before Swapping:");

Mr.Bibek Kumar-Assistant Professor-CSE


The Output Parameters
 Output parameters are used to pass results back to the calling method.
 This is achieved by declaring the parameters with an out keyword.
 Similar to reference parameter, out parameter does not create a new
storage location.
Example:-
Void output(out int x)
{
x=100;
}
int m; //m is uninitialized
output(out m); //value of m is set.

Mr.Bibek Kumar-Assistant Professor-CSE


The Output Parameters
using System;
class xyz
{
static void Square(int x, out int y)
{
y=x*x;
}
public static void Main()
{
int m;//need not be initialized
Square(10, out m);
Console.WriteLine("m= "+m);
}
}

Mr.Bibek Kumar-Assistant Professor-CSE


Variable Argument Lists
 In C#, we can define methods that can handle variable number of
arguments using what are known as PARAMETER ARRAYS.
 Parameter arrays are declared using the keyword params.
Void function1(params int [ ]x)
{
}
 Here, x has been declared as parameter array. This array must be one
dimensional arrays.
 A parameter may be a part of a formal parameter list and in such cases, it
must be the last parameter.
 The method function1 can be invoked in two ways:-
• Using int type array as a value parameter. ( function1(a);)
• Using zero or more int type arguments for the parameter array.(function
(10,20);)

Mr.Bibek Kumar-Assistant Professor-CSE


Variable Argument Lists
using System;
class XYZ
{
static void Parray(params int [ ] arr)
{
Console.Write("Array elements are:");
foreach(int i in arr)
{
Console.Write(" "+i);
Console.WriteLine();
}
}
public static void Main()
{
int [ ] x={11,22,33};
Parray(x);
Parray();
Parray(110,220);
}
}

Mr.Bibek Kumar-Assistant Professor-CSE

Vous aimerez peut-être aussi