c# string object code example
Example 1: how to declare a string c#
string MyString = "Your string in here";
Example 2: c# string methods
string string1 = "Today is " + DateTime.Now.ToString("D") + ".";
Console.WriteLine(string1);
string string2 = "This is one sentence. " + "This is a second. ";
string2 += "This is a third sentence.";
Console.WriteLine(string2);
Example 3: c# $ string
string color = blue;
// Both versions do the same thing.
Console.WriteLine("The sky is " + color);
Console.WriteLine($"The sky is {color}");
//Note the dollar ^sign and ^curly^ brackets.
Example 4: C# string
string str1 = "Blue";
string str2 = "Duck";
//returns length of string
str1.Length;
//Make clone of string.
str2 = str1.Clone();
//checks whether specified character or string is exists or not
//in the string value.
str2.Contains(“hack”);
//checks whether specified character is
//the last character of string or not.
str2.EndsWith(“io”);
//compares two string and returns Boolean value true
//as output if they are equal, false if not
str2.Equals(str1);
//Returns the index position of first occurrence of specified character.
str1.IndexOf(“:”);
//Converts String into lower case based on rules of the current culture.
str1.ToLower();
//Converts String into Upper case based on rules of the current culture.
str1.ToUpper();
//Insert the string or character in the string at the specified position.
str1.Insert(0, “Welcome”);
//Returns the index position of last occurrence of specified character.
str1.LastIndexOf(“T”);
//deletes all the characters from beginning to specified index position
str1.Remove(i);
//replaces the specified character with another
str1.Replace(‘a’, ‘e’);
//This method splits the string based on specified value.
string[] strArray = str1.Split(“/”);
//This method returns substring.
str1.Substring(startIndex , endIndex);
//It removes extra whitespaces from beginning and ending of string.
str1.Trim();
//returns HashValue of specified string.
str1.GetHashCode();
//This is not an exhaustive list.
Example 5: string $ c#
var jh = (firstName: "Jupiter", lastName: "Hammon", born: 1711, published: 1761);
Console.WriteLine($"{jh.firstName} {jh.lastName} was an African American poet born in {jh.born}.");
Console.WriteLine($"He was first published in {jh.published} at the age of {jh.published - jh.born}.");
Console.WriteLine($"He'd be over {Math.Round((2018d - jh.born) / 100d) * 100d} years old today.");
// Output:
// Jupiter Hammon was an African American poet born in 1711.
// He was first published in 1761 at the age of 50.
// He'd be over 300 years old today.