Photo Gallery

Thursday, August 10, 2017

Basic use of string in C Sharp

In this post, i will explain basic use of string in day to day programming but before going to see an example first let me give you the basic details of string.



In C#, string is a data type which represents Unicode character. Some of the interviewer asked question like, Is there any difference between string and String(re: with Capital S) ?

Answer is NO because that string is an alias for System.String so you can also write System.String instead of string.However you will have to import "using System" to use string in your C# project.

Examples of String
class Program
{
static void Main(string[] args)
{
string seperator = "===========================================================================\n";
string welcome = "Basic String Uses";
Console.WriteLine(welcome);
Console.WriteLine(seperator);
string firstName, lastName;
firstName = "Chintan";
lastName = "Patel";
// //Compare two string
Console.WriteLine("Is first Name and last name same? Answer is : " + firstName.Equals(lastName));
Console.WriteLine(seperator);
//Concatenation
string fullName = firstName + " " + lastName;
Console.WriteLine("Full Name: " + fullName.ToUpper());
//Replace
string myName = fullName.Replace("Patel", "");
Console.WriteLine("My Name is " + myName);
Console.WriteLine(seperator);
//Array Join
string[] arr = { "I", "am", "a", "Software", "Developer" };
string joinArray = String.Join(" ", arr);
Console.WriteLine(joinArray);
//String constructor
Console.Write("Working at ");
char[] company = { 'V', 'i', 'r', 't', 'u', 's', 'a', };
string work = new string(company);
Console.WriteLine(work);
Console.WriteLine(seperator);
//Check whether specified value exists or not in string
Console.WriteLine(work.Contains("Vir"));
Console.WriteLine(seperator);
DateTime dt = DateTime.Now;
string date = String.Format("Current date is {0:d}", dt);
string time = String.Format("Current time is {0:t}", dt);
Console.WriteLine(date);
Console.WriteLine(time);
Console.ReadLine();
}
}


Output




If you have any questions, post here. Also, provide your valuable suggestions and thoughts in form of comments in the section below.

Thank you !!!

No comments:

Post a Comment