string in c-sharp

40
String Manipulation IN C#

Upload: abhishek-garg

Post on 22-Apr-2017

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: String in C-sharp

String Manipulation IN C#

Page 2: String in C-sharp

A string is a sequential collection of Unicode characters, typically used to represent text, while a String is a sequential collection of System.Char objects that represents a string.

The value of the String is the content of the sequential collection, and the value is immutable.

A String is called immutable because its value cannot be modified once it has been created. Methods that appear to modify a String actually return a new String containing the modification. If it is necessary to modify the actual contents of a string-like object, use the System.Text.StringBuilder class.

String

Page 3: String in C-sharp

A String (note- uppercase S) is a fundamental type, managed by the .NET framework. A string (lowercase s) is an alias in C# for the .NET String type.you can use either interchangeably though selecting string and pressing the F1 key will give different help pages.

String

Page 4: String in C-sharp

We can create immutable string using string or String objects in a number of ways:

1. Assigning string literals2. ReadLine from the Keyboard3. Using ToString Method4. Copying from one object to another.5. Concatenating two objects

String

Page 5: String in C-sharp

string str; // declaring a string objectstr = "abc"; // assigning string literal

Both these statements may be combined into one as follows:string str = "abc";

1. DECLARING STRING(Assigning string Literals)

Page 6: String in C-sharp

It is possible to read a string value interactively from the keyboard and assign it to a string object.

string str = Console.ReadLine();

On reaching this statement, the system will wait for a string of characters to be entered from the keyboard. When the ‘return key’ is pressed, the string will be read and assigned to the string object.

2.READING STRING FROM THE KEYBOARD

Page 7: String in C-sharp

Another way of creating a string is to call the ToString method on an object and assign the result to a string variable.

int number = 123;string str = number.ToString();

“Convert” function handles NULLS while “i.ToString()” does not it will throw a NULL reference exception error. So as good coding practice using “convert” is always safe.

3. The ToString method

Page 8: String in C-sharp

You can create copies of existing strings. This can be done in two ways:Using the overloaded =operatorUsing the static Copy method

Example:string s2=s1 //assigningstring s2=string.Copy(s1); //copying

4. Copying strings

Page 9: String in C-sharp

You can also create new strings by concatenating existing strings.Using the overloaded +operatorUsing the static Concat method

Example:string s3=s1+s2 //s1 ,s2 already existstring s3=string.Concat(s1,s2);

5. Concatenating strings

Page 10: String in C-sharp

STRING METHODS

String objects are immutable,i.e we cannot modify the characters contained in them.string is an alias for the predefined System.String class in the CLR.

Compare()CompareTo() ToUpper()ConCat() Copy()CopyTo() EndsWith()Equals() IndexOf() Insert() Join()PadLeft() PadRight()Remove() Replace()Split() StartsWith()Substring() ToLOwer()ToUpper Trim()TrimEnd() TrimStart()

Page 11: String in C-sharp

CONCATENATING STRINGSWe can create new strings by concatenating existing strings. This can be done in two ways1. Using the overloaded + operator

string str3 = str1 + str2;Example:string start = "This is a "; string end = "concatenated string!"; string concat = start + end;

2. Using the static Concate method string str2 = string.Concat(str1,str2);Example:string start = "This is a "; string end = "concatenated string!"; string concat = string.Concat(start, end);Note: the original strings are unchanged in first case.

Page 12: String in C-sharp

The String class provides a method that inserts one string into the middle of another. The Insert method acts upon an existing string variable or literal and requires two parameters. Syntax:String.Insert(index,string)The first parameter is an integer that indicates the position where the second string is to be inserted. This integer counts characters from the left with zero indicating that the insertion will be at the beginning of the string. The second parameter is the string to be inserted.

Examplestring template = "Please ask for on arrival."; string tutor = "Lisa"; Console.WriteLine(template.Insert(15, tutor));

// Outputs: "Please ask for Lisaon arrival."

INSERT

Page 13: String in C-sharp

Removing Characters from a String

The Remove method allows characters to be deleted from a string, shortening the string accordingly. There are two overloads available. The first requires a single parameter to indicate the start

position for the character removal. The second overload adds a second parameter specifying how

many characters to delete. Any further characters are unaffected.Remove(in start index);Remove(int start index, int length);Example:

string sample = "The quick brown fox jumps over the lazy dog."; string result = sample.Remove(16); // result = "The quick brown " result = sample.Remove(16, 24);

Page 14: String in C-sharp

JOIN() and SPLIT()

Join takes a String array and a separator string and produces a single string with one separator between each element in the array.

Split does the opposite, splitting a string made up of several elements separated by a separator, or when you want to split a string using delimiter.

Page 15: String in C-sharp

class Program { static void Main(string[] args) { string commatext = "alpha,beta.gamma"; string[] words = commatext.Split('a'); Console.WriteLine("Dashed join is {1}",words); Console.WriteLine("Dashed join is {2}", words); Console.WriteLine("Dashed join is {3}", words); Console.WriteLine("Dashed join is {4}", words); Console.WriteLine("Dashed join is {5}", words); Console.ReadLine();}}

Output:Dashed join is lphDashed join is ,betDashed join is .gDashed join is mmDashed join is

Example of Split

Page 16: String in C-sharp

class Program { static void Main(string[] args) { string commatext = "alpha,beta.gamma"; string[] words = commatext.Split('a'); string dashed = string.Join("&", words); Console.WriteLine("Dashed join is {0}", dashed);

Console.ReadLine();

}

Output:Dashed join is &lph&,bet&.g&mm&

Example of Join and Split

Page 17: String in C-sharp

class Program { static void Main(string[] args) { string commatext = "alpha,beta.gamma"; string[] words = commatext.Split(',');

Console.WriteLine(“words after split {0}", words);Console.WriteLine(“words after split {1}", words); string dashed = string.Join("---", words); Console.WriteLine("Dashed join is {0}", dashed); string[] words1 = commatext.Split('.'); string dashed1 = string.Join("---", words1); Console.WriteLine("Dashed join is {0}", dashed1);

Console.ReadLine();

}

Output:words after split : alphawords after split beta.gammaDashed join is alpha---beta.gammaDashed join is alpha,beta---gamma

Example of Join and Split

Page 18: String in C-sharp

PadLeft and PadRight

These two functions pad a string to the left or right with to the specified length. By default the character is a space but an overload lets you specify an alternative char. String.PadLeft(total width,padding character);Note that these methods return a new string. Syntax:

x.PadRight(x.Length + 10) ; will NOT add ten spaces to x (assuming x is a string).

Example: string y = x.PadRight(x.Length + 10) string y = x.PadLeft(x.Length + 10,'&');

string s11 = x.PadRight((60) , '*');

Page 19: String in C-sharp

StartsWith and EndsWith

Both methods return true or false if a string starts or ends with the specified string. Using the example

string s1 = "".PadRight(60) + '*'; string s2 = “HaI”

if (s1.StartsWith(" "))    Console.WriteLine("S1 starts with spaces") ;

Page 20: String in C-sharp

Extracting Text from a String

The Substring method discards the start and end and returns the middle section. Syntax:Substring(in start index);Substring(int start index, int length);Example:string sample = "The quick brown fox jumps over the lazy dog.";

string result = sample.Substring(16); // result = "fox jumps over the lazy dog.“ result = sample.Substring(16, 5); // result = "fox j"

Page 21: String in C-sharp

Search and Replace

Replace()The method accepts two parameters. The first is the string to search for and the second is the string to use as a substitute. When executed, all instances of the first string are automatically replaced.synataxReplace( char old_char, char new_char);Example:string sample = "The brown fox."; string result = sample. Replace("brown", "red");

OutputThe red fox

Page 22: String in C-sharp

We can create copies of existing strings. This can be done in two ways1. Using the overloaded = operator2. Using the static Copy method

Example:String str2 = str1; //assigningString str2 = string.copy(str1); //copying

Example:string sample = "The brown fox."; string result = string.Copy(sample); outputresult ="The brown fox.”

COPYING STRING

Page 23: String in C-sharp

ToUpper, ToLower function.

Coverts all the characters from a String into upper/lower case. Example: String st = " String Manipulation in C# ";String a3 = st.ToUpper();String a4=st.ToLower();Console.WriteLine(“uppercase”+a3);Console.WriteLine(“Lowercase”+a4);

Page 24: String in C-sharp

Trim Function

The trim function strips all white spaces form both start and end form a given string. It has two other variants, the TrimStart and TrimEnd.

Example:

string st = " welcome to thapar ";String trimed = st.Trim();Console.WriteLine("Original: " + st);Console.WriteLine("Using Trim: " + "=" + trimed +"=");String trimedStart = st.TrimStart();Console.WriteLine("1st TrimStart: " + trimedStart + "=");

Output:Original: welcome to thaparUsing Trim: =welcome to thapar=1st TrimStart: welcome to thapar =1st TrimEND: welcome to thapar=

Page 25: String in C-sharp

COMPARING STRING

Compare() method

int n= string.Compare(s1,s2);Where s1 and s2 are stringsZero integer if s1 equals to s2.A positive integer , if s1 >s2A negative integer , if s1<s2

It can take bool type parameter also, to decide whether case should be ignored or not. If the bool parameter is true ,case is ignored.

int n = string.Compare(a1,a2,true);

If(string.Compare(a1,a2)==0)Console.WriteLine(“they are equal”);

Page 26: String in C-sharp

COMPARING STRING

Equals() methodThere are two versions of Equals methodbool b1=s2.Equals(s1);bool b2=string.Equals(s2,s1);These methods return a Boolean value true if s1 and s2 are equal, otherwise false.

The == operatorbool b3=(s1==s2);b3 is true if s1 and s2 are equalOrIf(s1==s2)Console.WriteLine(“they are equal”);

Page 27: String in C-sharp

ARRAYS OF STRINGS

string[] itemarray=new string[3];:it creates an array of size 3 to hold 3 strings.

String[] itemarray={“java”,”C#”,”C++”};

The size of an array is determined by the number of elements in the initialization list.

Page 28: String in C-sharp

class Program { static void Main(string[] args) { StringBuilder st1=new StringBuilder("xyz",2); String[] itemarray={"java","C#","C++"}; int n = itemarray.Length; Array.Sort(itemarray); for (int i = 0; i < n; i++) { Console.WriteLine(itemarray[i]); } Console.ReadLine(); //Reverse array Array.Reverse(itemarray); for (int i = 0; i < n; i++) { Console.WriteLine(itemarray[i]); }}}

Page 29: String in C-sharp

The String object is immutable. Whenever we use one of the methods in the System.String class, we create a new string object in memory, which requires a new allocation of space for that new object.

When we need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

STRINGBUILDER

Page 30: String in C-sharp

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object.

StringBuilder objects are mutable.StringBuilder st1=new StringBuilder(“adsh”,4);StringBuilder st1=new StringBuilder(“adsh”);StringBuilder st2= new StringBuilder();StringBuilder st2= new StringBuilder(2);

For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

The System.Text namespace contains the StringBulider class.

Include using System.Text in the code.

STRINGBUILDER

Page 31: String in C-sharp

Append():Appends a string

EnsureCapacity():Ensure sufficient size

Insert():Insert a string at a specified location

Remove():Remove the specified character

Replace():Replaces all instances of a character with a

specified one

StringBuilder Methods

Page 32: String in C-sharp

Capacity: To retrieve or set the number of characters the object can hold.

Length: To retrieve or set the Length.

MaxCapacity :To retrieve the maximum capacity of the object.

StringBuilder Properties

Page 33: String in C-sharp

Capacity:the StringBuilder is a dynamic object that allows you to expand the number of characters in the string that it encapsulates, you can specify a value for the maximum number of characters that it can hold. This value is called the capacity of the object .

StringBuilderProperty

Page 34: String in C-sharp

EnsureCapacityThe EnsureCapacity method can be used to check the capacity of the current StringBuilder. If the capacity is greater than the passed value, no change is made; however, if the capacity is smaller than the passed value, the current capacity is changed to match the passed value.LengthThe Length property can also be viewed or set. If you set the Length property to a value that is greater than the Capacity property, the Capacity property is automatically changed to the same value as the Length property. Setting the Length property to a value that is less than the length of the string within the current StringBuilder shortens the string.

Page 35: String in C-sharp

using System;using System.Text;

class StringBuilderFeatures{ static void Main(string[] args) { StringBuilder buffer = new StringBuilder("Hello, how are you?");

string output = "buffer = " + buffer.ToString() +"\nLength = " + buffer.Length + "\nCapacity = " + buffer.Capacity; buffer.EnsureCapacity(75); output += "\n\nNew capacity = " + buffer.Capacity; // truncate StringBuilder by setting Length property buffer.Length = 10; output += "\n\nNew length = " + buffer.Length + "\nbuffer = "; // use StringBuilder indexer for (int i = 0; i < buffer.Length; i++) output += buffer[i]; Console.WriteLine(output); Console.ReadLine(); }}

Output:buffer = Hello, how are you?Length = 19Capacity = 19

New capacity = 75

New length = 10buffer = Hello, how

Example

Page 36: String in C-sharp

public StringBuilder AppendFormat( string format, Object arg0 )

APPENDFORMAT() example

using System;using System.Text;class Sample{ static StringBuilder sb = new StringBuilder(); public static void Main() { int var1 = 111; float var2 = 2.22F; string var3 = "abcd"; Console.WriteLine(); Console.WriteLine("StringBuilder.AppendFormat method:"); sb.AppendFormat("1) {0}", var1); Show(sb); sb.AppendFormat("2) {0}, {1}", var1, var2); Show(sb); sb.AppendFormat("3) {0}, {1}, {2}", var1, var2, var3); Show(sb);

Console.ReadLine(); }

Page 37: String in C-sharp

continuation APPENDFORMAT()

public static void Show(StringBuilder sbs) { Console.WriteLine(sbs.ToString()); sb.Length = 0; }}

Output:

StringBuilder.AppendFormat method:1) 1112) 111, 2.223) 111, 2.22, abcd

Page 38: String in C-sharp

using System;using System.Text;class Class1 { public static void Main(string[] args) { string str1; string str2; Console.WriteLine("Please enter the string"); str1 = Console.ReadLine(); Console.WriteLine("Please enter the string"); str2=Console.ReadLine(); StringBuilder builder1 = new StringBuilder(str1, 4); StringBuilder builder2 = new StringBuilder(str2, 6); int cap = builder1.EnsureCapacity(23); Console.Write("STRING STR1 APPENDED TO:"); builder1.Append("HELLO "); Console.WriteLine(builder1); builder2.Insert(2,“ABCDE"); Console.WriteLine(builder2); builder2.Remove(2, 4); Console.WriteLine(builder2); Console.ReadLine(); } }

Example of StringBuilder

Page 39: String in C-sharp
Page 40: String in C-sharp

To print on console:

String output = "hello" + buffer.MaxCapacity;