String manipulation in C# involves working with immutable String objects. Key concepts covered include:
1. Strings are immutable sequences of characters that cannot be modified, though methods like Replace return new strings.
2. Common string operations include concatenation using + or Concat(), copying using = or Copy(), searching/replacing with methods like IndexOf, Replace, and extracting substrings with Substring.
3. Other useful methods are Trim/TrimStart/TrimEnd for whitespace, PadLeft/PadRight for padding, Join for combining arrays, and Split for splitting.
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
96 views
String in C-Sharp
String manipulation in C# involves working with immutable String objects. Key concepts covered include:
1. Strings are immutable sequences of characters that cannot be modified, though methods like Replace return new strings.
2. Common string operations include concatenation using + or Concat(), copying using = or Copy(), searching/replacing with methods like IndexOf, Replace, and extracting substrings with Substring.
3. Other useful methods are Trim/TrimStart/TrimEnd for whitespace, PadLeft/PadRight for padding, Join for combining arrays, and Split for splitting.
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40
String Manipulation IN C#
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 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 We can create immutable string using string or String objects in a number of ways:
1. Assigning string literals 2. ReadLine from the Keyboard 3. Using ToString Method 4. Copying from one object to another. 5. Concatenating two objects
Both these statements may be combined into one as follows: string str = "abc";
1. DECLARING STRING(Assigning string Literals) 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 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 You can create copies of existing strings. This can be done in two ways: Using the overloaded =operator Using the static Copy method
5. Concatenating strings 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.
CONCATENATING STRINGS We can create new strings by concatenating existing strings. This can be done in two ways 1. 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.
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.
Example string template = "Please ask for on arrival."; string tutor = "Lisa"; Console.WriteLine(template.Insert(15, tutor));
// Outputs: "Please ask for Lisaon arrival." INSERT 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); 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.
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 lph Dashed join is ,bet Dashed join is .g Dashed join is mm Dashed join is
Example of Split
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
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 : alpha words after split beta.gamma Dashed join is alpha---beta.gamma Dashed join is alpha,beta---gamma
Example of Join and Split 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) , '*'); 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") ;
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" 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. synatax Replace( char old_char, char new_char); Example: string sample = "The brown fox."; string result = sample. Replace("brown", "red");
Output The red fox We can create copies of existing strings. This can be done in two ways 1. Using the overloaded = operator 2. Using the static Copy method
Example: string sample = "The brown fox."; string result = string.Copy(sample);
output result ="The brown fox. COPYING STRING 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);
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.
Output: Original: welcome to thapar Using Trim: =welcome to thapar= 1st TrimStart: welcome to thapar = 1st TrimEND: welcome to thapar=
COMPARING STRING Compare() method
int n= string.Compare(s1,s2); Where s1 and s2 are strings Zero integer if s1 equals to s2. A positive integer , if s1 >s2 A 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);
COMPARING STRING Equals() method There are two versions of Equals method bool 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 == operator bool b3=(s1==s2); b3 is true if s1 and s2 are equal Or If(s1==s2) Console.WriteLine(they are equal);
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.
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]);
} } }
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 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 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 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 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 EnsureCapacity The 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. Length The 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.
using System; using System.Text;
class StringBuilderFeatures { static void Main(string[] args) { StringBuilder buffer = new StringBuilder("Hello, how are you?");
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(); } }