- Back to Home »
- C#.NET »
- C#.NET String Functions
Posted by :
Sudhir Chekuri
Thursday, 31 December 2015
ToUpper and ToLower
ToUpper function is used to convert a whole string into uppercase andToLower function is used to convert a whole string into lowercase.
Example program to convert a string into lowercase and lowercase
Program
using System;
namespace UpperLower
{
class Program
{
static void Main(string[] args)
{
string str1 = "suDHir";
string s4 = str1.ToLower(); //converting into lowercase
Console.WriteLine(s4);
s4 =
str1.ToUpper(); //converting into uppercase
Console.WriteLine(s4);
Console.ReadKey();
}
}
}
sudhir
SUDHIR
Remove
Remove fuction is used to remove a part of a string by giving the starting index of the string and number of characters to be removed.Example program to remove a part of string
Program
using System;
namespace Remove
{
class Program
{
static void Main(string[] args)
{
string str = "sudhir";
string s3 = str.Remove(1, 3); //removing characters from index
1, and removing 3 characters ie., udh
Console.WriteLine(s3);
Console.ReadKey();
}
}
}
sir
Trim
Trim function is used to remove the white spaces from both the ends of the string.Along with Trim function we also have TrimStart() and TrimEnd().
TrimStart is used to trim the white spaces at the starting of the string
TrimEnd is used to trim the white spaces at the end of the string.
Example program for Trim, TrimStart and TrimEnd
Program
using System;
namespace Trim
{
class Program
{
static void Main(string[] args)
{
string s = " hello
";
string tr = s.Trim();
Console.WriteLine(tr);
string tst = s.TrimStart();
Console.WriteLine(tst);
string tend = s.TrimEnd();
Console.WriteLine(tend);
Console.ReadKey();
}
}
}
_hello_
_hello _
_ hello_
Replace
Replace function is used to replace an old string with a new string.Syntax: string s2=s1.Replace(old string,new string);
Example program for Replace
Program
using System;
namespace Replace
{
class Program
{
static void Main(string[] args)
{
string s = "hello";
string s2 = s.Replace("hello", "hai");
Console.WriteLine(s2);
Console.ReadKey();
}
}
}
hai
IndexOf
Used to find substring within a string and return its starting index value.
Example program for IndexOf
Program
using System;
namespace IndexOf
{
class Program
{
static void Main(string[] args)
{
string s = "hellohai";
string s1 = "hai";
int i = s.IndexOf(s1);
Console.WriteLine(i);
Console.ReadKey();
}
}
}
5