You are on page 1of 3

Textbook

Chapter 12
Some essential operators of String type

Replace

{
string str;
Console.WriteLine("Enter sentence whatever you want");
str = Convert.ToString(Console.ReadLine());
str = str.Replace("a", "A");
Console.WriteLine(str);
Console.ReadKey();
}

Or following code is also returns the same result.


{
string str;
Console.WriteLine("Enter sentence whatever you want");
str = Convert.ToString(Console.ReadLine());
Console.WriteLine(str.Replace("a", "A"));
Console.ReadKey();
}

In the brackets of Replace operator, first expression represents the old symbol
or word which is situated in our text, second expression reflects our desired
symbol or word which we want to enter it.

{
string str;
Console.WriteLine("Enter sentence whatever you want");
str = Convert.ToString(Console.ReadLine());
str = str.Replace(" ", "");
Console.WriteLine(str);
Console.ReadKey();
}

By using this code we can erase all spaces of the text.


Remove method
{
string str;
Console.WriteLine("Enter sentence whatever you want");
str = Convert.ToString(Console.ReadLine());
str=str.Remove(3,3);
Console.WriteLine(str);
Console.ReadKey();
}

In the brackets of Remove operator, first number describes the start index which
we want to erase and second number describes the length of erased text (how
many index will delete from our text).
If we want to delete the last 3 symbols of the sentence, we can write like that.
{
string str;
Console.WriteLine("Enter sentence whatever you want");
str = Convert.ToString(Console.ReadLine());
Console.WriteLine(str.Remove(str.Length-3,3));
Console.ReadKey();
}

The combination of the Replace and Remove operator


Convert this sentence (My name is Ali) to the other sentence (I am Ali) by using
Replace and Remove operator.
{
string str="My name is Ali";
str = str.Replace("My", "I");
str = str.Replace("is", "am");
str = str.Remove(3, 5);
Console.WriteLine(str);
Console.ReadKey();
}

Insert
{
string str;
string a = " Group";
Console.WriteLine("Enter sentence whatever you want");
str = Convert.ToString(Console.ReadLine());
string k = str.Insert(6, a);
Console.WriteLine(k);
Console.ReadKey();
}

In the brackets of Insert operator, first number means the beginning index,
which we want to insert our text from it, other number reflects our text we will
include.
Conversion
Convert this sentence (We use from C# program’s advantages) to the other
sentence (We study C# programming) by using Replace, Remove and Insert
operator.
{
string str = "We use from C# program’s advantages";
string a = "ming";
str = str.Remove(22, 2);
str = str.Insert(22, a);
str = str.Remove(7, 5);
str = str.Replace("use", "study");
str = str.Replace("advantages", "language");
Console.WriteLine(str);
Console.ReadKey();
}

You might also like