String
• a string is a series of characters that is used to represent text. It can be a
character, a word or a long passage surrounded with the double quotes
".
• There are two types of string in C#:
• 1. Immutable strings
• 2. Mutable strings
• The immutable strings are can’t be modify while mutable strings are
modifiable.
• C# also supports a feature of regular expression that can be used for
complex strings manipulations and pattern matching.
string provides various methods to perform
different operations on strings.
• Get the Length of a string:
• To find the length of a string, we use the Length property.
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "C# Programming";
Console.WriteLine("string: " + str);
int length = str.Length;
Console.WriteLine("Length: "+ length);
Console.ReadLine();
}
}
}
Join two strings in C#
• We can join two strings in C# using the Concat() method.
• using System;
• namespace CsharpString {
• class Test {
• public static void Main(string [] args) {
• string str1 = "C# ";
• Console.WriteLine("string str1: " + str1);
• string str2 = "Programming";
• Console.WriteLine("string str2: " + str2);
•
• string joinedString = string.Concat(str1, str2);
• Console.WriteLine("Joined string: " + joinedString);
• Console.ReadLine();
• }
• }
• }
C# compare two strings
• In C#, we can make comparisons between two strings using the Equals() method. The
Equals() method checks if two strings are equal or not.
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
Boolean result1 = str1.Equals(str2);
Console.WriteLine("string str1 and str2 are equal: " + result1);
Boolean result2 = str1.Equals(str3);
Console.WriteLine("string str1 and str3 are equal: " + result2);
Console.ReadLine();
}
}
}
String interpolation
• string interpolation to insert variables inside a string. For string interpolation, the
string literal must begin with the $ character.
• using System;
• namespace CsharpString {
• class Test {
• public static void Main(string [] args) {
• string name = "Programiz";
• string message = $"Welcome to {name}";
• Console.WriteLine(message);
• Console.ReadLine();
• }
• }
• }
C# uses the + operator for both
addition and concatenation.
• int x = 10; • string x = "10";
• int y = 20; • string y = "20";
• int z = x + y; • string z = x + y;
String Concatenation
• string firstName = "John ";
• string lastName = "Doe";
• string name = firstName + lastName;
• Console.WriteLine(name);
• string firstName = "John ";
• string lastName = "Doe";
• string name = string.Concat(firstName, lastName);
• Console.WriteLine(name);
String Compare()
• Rule
• s1==s2 returns 0
• s1>s2 returns 1
• s1<s2 returns -1
• first: first argument represents string which is to be compared with second string.
• second: second argument represents string which is to be compared with first string.
• Return
• It returns an integer value.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "hello";
• string s2 = "hello";
• string s3 = "csharp";
• string s4 = "mello";
•
• Console.WriteLine(string.Compare(s1,s2));
• Console.WriteLine(string.Compare(s2,s3));
• Console.WriteLine(string.Compare(s3,s4));
• }
• }
String CompareOrdinal()
• s1==s2 returns 0
• s1>s2 returns positive number in difference
• s1<s2 returns negative number in difference
• Parameters
• first: first argument represents string which is to be compared with second string.
• second: second argument represents string which is to be compared with first
string.
• Return
• It returns an integer value.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "hello";
• string s2 = "hello";
• string s3 = "csharp";
• string s4 = "mello";
•
• Console.WriteLine(string.CompareOrdinal(s1,s2));
• Console.WriteLine(string.CompareOrdinal(s1,s3));
• Console.WriteLine(string.CompareOrdinal(s1,s4));
• }
• }
String CompareTo()
• CompareTo() method is used to compare String instance with a
specified String object.
• It indicates whether this String instance precedes, follows, or appears
in the same position in the sort order as the specified string or not.
• Parameters
• str: it is a string argument which is used to compare.
• Return
• It returns an integer value.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "hello";
• string s2 = "hello";
• string s3 = "csharp";
• Console.WriteLine(s1.CompareTo(s2));
• Console.WriteLine(s2.CompareTo(s3));
• }
• }
Use CompareTo method
• if (author1.CompareTo(author2) == 0)
• Console.WriteLine($"Both strings have same value.");
• else if (author1.CompareTo(author2) < 0)
• Console.WriteLine($"{author1} precedes {author2}.");
• else if (author1.CompareTo(author2) > 0)
• Console.WriteLine($"{author1} follows {author2}.");
String Contains()
• Contains() method is used to return a value indicating whether the
specified substring occurs within this string or not. If the specified
substring is found in this string, it returns true otherwise false.
• Parameters
• str: it is a string object which is used to check occurrence in the
calling string.
• Return
• It returns boolean value either true or false.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello ";
• string s2 = "He";
• string s3 = "Hi";
• Console.WriteLine(s1.Contains(s2));
• Console.WriteLine(s1.Contains(s3));
•
• }
• }
String Copy()
• Copy() method is used to create a new instance of String with the
same value as a specified String. It is a static method of String class.
Its return type is string.
• Parameter
• str: it takes a string argument which is used to create a copy of
specified string.
• Return
• It returns string object.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello ";
• string s2 = string.Copy(s1);
• Console.WriteLine(s1);
• Console.WriteLine(s2);
• }
• }
String CopyTo()
• CopyTo() method is used to copy a specified number of characters
from the specified position in the string. It copies the characters of
this string into a char array.
• Syntax:
• public void CopyTo(int sourceIndex, char[] destination,
• int destinationIndex, int count)
using System;
class Geeks {
public static void Main()
{
string str2 = “Program to C#";
char[] dest = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };
// str index 8 to 8 + 5 has
// to copy into Copystring
// 5 is no of character
// 6 is start index of Copystring
str2.CopyTo(8, dest, 6, 5);
// Displaying the result
Console.Write("String Copied in dest is: ");
Console.WriteLine(dest);
}
}
Output:
String Copied in dest is: Hello to C
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C#, How Are You?";
• char[] ch = new char[15];
• s1.CopyTo(10,ch,0,12);
• Console.WriteLine(ch);
• }
• }
String EndsWith()
• EndsWith() method is used to check whether the specified string
matches the end of this string or not.
• If the specified string is found at the end of this string, it returns true
otherwise false.
• Parameters
• str: it is a string object which is used to check the whether a specified
string ends with it.
• Return
• It returns boolean value either true or false.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello";
• string s2 = "llo";
• string s3 = "C#";
• Console.WriteLine(s1.EndsWith(s2));
• Console.WriteLine(s1.EndsWith(s3));
• }
• }
String Equals()
• Equals() method is used to check whether two specified String objects
have the same value or not. If both strings have same value, it return
true otherwise false.
• In other words, it is used to compare two strings on the basis of
content.
• Parameter
• str: it is a string object.
• Return
• It returns boolean value either true or false.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello";
• string s2 = "Hello";
• string s3 = "Bye";
• Console.WriteLine(s1.Equals(s2));
• Console.WriteLine(s1.Equals(s3));
• }
• }
Remove()
• Remove() method is used to get a new string after removing all the
characters from specified beginIndex till given length.
• If length is not specified, it removes all the characters after
beginIndex.
• Parameter
• index: it is an integer type parameter.
• Return
• It returns a string.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C#";
• string s2 = s1.Remove(2);
• Console.WriteLine(s2);
• }
• }
• Output:
• He
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "abcdefghijk";
• string s2 = s1.Remove(4, 5);
• Console.WriteLine(s2);
• }
• }
• Output:
• abcdjk
String Replace()
• Replace() method is used to get a new string in which all occurrences
of a specified Unicode character in this string are replaced with
another specified Unicode character.
• Parameter
• first: it is a first parameter of char type.
• second: it is a second parameter of char type.
• Return
• It returns a string.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello F#";
• string s2 = s1.Replace('F','C');
• Console.WriteLine(s2);
• }
• }
•
• Output:
• Hello C#
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C#, Hello .Net, Hello Javatpoint";
• string s2 = s1.Replace("Hello","Cheers");
• Console.WriteLine(s2);
• }
• }
• Output:
• Cheers C#, Cheers .Net, Cheers Javatpoint
String Split()
• The C# Split() method is used to split a string into substrings on the
basis of characters in an array. It returns string array.
• Parameter
• ch: it is a character type array.
• Return
• It returns array of string
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C Sharp";
• string[] s2 = s1.Split(' ');
• foreach (string s3 in s2)
• {
• Console.WriteLine(s3); o/p:
Hello
• } C
Sharp
• }
• }
String StartsWith()
• StartsWith() method is used to check whether the beginning of this
string instance matches the specified string.
• Parameter
• str: it is string type parameter which is used to check beginning of
string.
• Return
• It returns boolean value.
• using System;
•
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C Sharp";
• bool b1 = s1.StartsWith("h");
• bool b2 = s1.StartsWith("H");
• Console.WriteLine(b1);
• Console.WriteLine(b2);
• }
• }
String SubString()
• SubString() method is used to get a substring from a String. The
substring starts at a specified character position and continues to the
end of the string.
• Parameter
• index: it is an integer type parameter which is used to pass index to
get a substring.
• Return
• It returns a string.
• using System;
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C Sharp";
• string s2 = s1.Substring(5);
• Console.WriteLine(s2);
• }
• }
• Output:
• C Sharp
String ToCharArray()
• ToCharArray() method is used to get character array from a string
object.
• Parameter
• First method does not take any parameter while second method takes
two integer parameters.
• Return
• It returns a character array.
• using System;
• public class StringExample
Output:
•{
H
• public static void Main(string[] args) e
l
• { l
o
• string s1 = "Hello C#";
• char[] ch = s1.ToCharArray(); C
#
• foreach(char c in ch){
• Console.WriteLine(c);
• }
• }
•}
String ToLower()
• ToLower() method is used to convert a string into lowercase. It
returns a string in lower case.
• Parameter
• First method does not take any parameter.
• Return
• It returns a string.
• using System;
• Output:
• public class StringExample
hello c#
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C#";
• string s2 = s1.ToLower();
• Console.WriteLine(s2);
• }
• }
String ToString()
• ToString() method is used to get instance of String.
• Parameter
• It does not any parameter.
• Return
• It returns a string object.
• using System;
•
• public class StringExample
• {
• public static void Main(string[] args)
• {
• string s1 = "Hello C#";
• int a = 123;
• string s2 = s1.ToString();
• string s3 = a.ToString();
• Console.WriteLine(s2);
• Console.WriteLine(s3);
• }
• }
String Trim()
• Trim() method is used to remove all leading and trailing white-space
characters from the current String object.
• Parameter
• First method does not take any parameter. Second method takes a
char array as parameter.
• Return
• It returns a string.
• using System;
• public class StringExample
•{
• public static void Main(string[] args)
• {
• string s1 = "Hello C#";
• string s2 = s1.Trim();
• Console.WriteLine(s2);
• }
•}
Mutable String
• Mutable strings are those strings, which can be modifying
dynamically. This type of strings are created using StringBuilder class.
• StringBuilder sl = new StringBuilder (“welcome”);
• StringBuilder s2 = new StringBuilder ( );
using system.Text; // For using StringBuilder
using system;
class strMethod {
public static void Main( ) {
StringBuilder s = new stringBui1der(“c”};
console.writeLine(” stored string is :”+ s);
console.writeLine(“Length of string is :”+s.Length);
s.Append(“Sharp “); //. appending the string s
Console.writeLine(“After Append String is :”+ s);
console.writeLine(“Length of string is :”+s.Length);
s.Insert(7,”Language”); // inserting the string at last in s
console.writeLine(“After Insertion String is:”+ s);
console.writeLine(“Length of string is :”+s.Length);
int n = s.Length;
s [n] = “!”;
console.writeLine (” At Last String is:”+ s);
}
}
• StringBuilder.Append(string value) Method
• The Append method can be used to add or append a string value of
an object to the end of a string represented by the
current StringBuilder object
• StringBuilder.Insert(int index, string value) method
• This method inserts the string at specified index
in StringBuilder object.