Strings are an array of characters. They are stored as a sequential read only collection of char objects in the system internally. Strings in C# don't contain null characters in the end.
There are various methods to declare and initialize strings. Some of these are given as follows:
1. The string is only declared and not initialized. This is given below:
string str;
2. The string is declared and initialized to NULL. This is given below:
string str = NULL:
3. The string is declared and initialized to a sequence of characters. This is given below:
string str = “C# is fun”;
4. The String constructor can be used when a string is created from char*, char[ ] or sbyte*. This is given below:
char[ ] alphabets = { ‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’}; string str = new string(alphabets);
The different constructors and their description is given as follows:
Table: Constructors in String in C#
Source: MSDN
Constructors | Description |
---|---|
String (Char*) | This constructor initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters. |
String(Char[]) | This constructor initializes a new instance of the String class to the value indicated by an array of Unicode characters. |
String(SByte*) | This constructor initializes a new instance of the String class to the value indicated by a pointer to an array of 8-bit signed integers. |
String(Char, Int32) | This constructor initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times. |
String(Char*, Int32, Int32) | This constructor initializes a new instance of the String class to the value indicated by a specified pointer to an array of Unicode characters, a starting character position within that array, and a length. |
String(Char[], Int32, Int32) | This constructor initializes a new instance of the String class to the value indicated by an array of Unicode characters, a starting character position within that array, and a length |
String(SByte*, Int32, Int32) | This constructor initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, and a length. |
String(SByte*, Int32, Int32, Encoding) | This constructor initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an Encoding object. |
The different properties and their description is given as follows:
Table: Properties in String in C#
Source: MSDN
Properties | Description |
---|---|
Chars [Int32] | This property gets the Char object at a specified position in the current String object. |
Length | This property gets the number of characters in the current String object. |
The different methods and their description is given as follows:
Table: Methods in String in C#
Source: MSDN
Methods | Description |
---|---|
Clone() | This method returns a reference to the given instance of String. |
Compare() | This method compares two specified String objects and returns an integer that indicates their relative position in the sort order. |
CompareTo() | This method compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String. |
Concat() | This method concatenates one or more instances of String, or the String representations of the values of one or more instances of Object. |
Copy() | This method creates a new instance of String with the same value as the specified String. |
Equals() | This method determines whether two String objects have the same value. |
Format() | This method converts the value of objects to strings based on the formats specified and inserts them into another string. |
Insert() | This method returns a new string in which a specified string is inserted at a specified index position in this instance. |
Join() | This method concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. |
PadLeft() | This method returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character. |
PadRight() | This method returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character. |
Remove() | This method returns a new string in which a specified number of characters from the current string are deleted. |
Replace() | This method returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String. |
Split() | This method returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array. |
ToLower() | This method returns a copy of the string converted to lowercase. |
ToString() | This method converts the value of this instance to a String. |
ToUpper() | This method returns a copy of this string converted to uppercase. |
Trim() | This method returns a new string in which all leading and trailing occurrences of a set of specified characters from the current String object are removed. |
Some of the programs related to strings are given below:
The program to find the length of a string is given as follows:
Source Code: Program to find length of string in C#
using System; namespace StringDemo { class Example { static void Main(string[] args) { string str = "Laptops and Mobiles"; Console.WriteLine("The Length of the string \"{0}\" is : {1} ",str, str.Length); } } }
The output of the above program is as follows:
The Length of the string "Laptops and Mobiles" is : 19
Comparing Two Strings
A program to compare two strings and find if they are equal or not is given as follows:
Source Code: Program to compare two strings in C#
using System; namespace StringDemo { class Example { static void Main(string[] args) { string s1 = "Apple"; string s2 = "Apple"; if (String.Compare(s1, s2) == 0) { Console.WriteLine("The strings are equal"); } else { Console.WriteLine("The strings are not equal"); } } } }
The output of the above program is as follows:
The strings are equal
A program that obtains the last 4 characters from a string is given as follows:
Source Code: Program to obtain the last 4 characters from a string in C#
using System; public class Demo { public static void Main() { string str = "Strings in C#"; string resultStr = str.Substring(str.Length - 4); Console.WriteLine("Original string: {0}", str); Console.WriteLine("Resultant string: {0}", resultStr); } }
The output of the above program is as follows:
Original string: Strings in C# Resultant string: n C#
A program that obtains the last 2 characters from a string using Regex is given as follows:
Source Code: Program to obtain the last 2 characters from a string using Regex in C#
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string str = "Strings in C#"; Console.WriteLine("Original string: {0}", str); Console.Write("Resultant string: "); Console.WriteLine(Regex.Match(str,@"(.{2})\s*$")); } }
The output of the above program is as follows:
Original string: Strings in C# Resultant string: C#
A program that prints the first letter of each word in a string using Regex is given as follows:
Source Code: Program to print the first letter of each word in a string using Regex in C#
using System; using System.Text.RegularExpressions; namespace RegexDemo { public class Example { private static void showMatch(string str, string exp) { Console.WriteLine("The string: " + str); Console.WriteLine("The Expression: " + exp); MatchCollection matchCol = Regex.Matches(str, exp); foreach (Match m in matchCol) { Console.WriteLine(m); } } public static void Main(string[] args) { string str = "Strings in C#"; Console.WriteLine("Display first letter of each word!"); showMatch(str, @"\b[a-zA-Z]"); } } }
The output of the above program is as follows:
Display first letter of each word! The string: Strings in C# The Expression: \b[a-zA-Z] S i C
A program that prints the first letter of each word in a string is given as follows:
Source Code: Program to print the first letter of each word in a string in C#
using System; public class Example { public static void Main() { string str = "Strings in C#"; Console.WriteLine("String is: " + str); Console.WriteLine("Displaying first letter of each word"); string[] splitString = str.Split(); foreach(string i in splitString) { Console.WriteLine(i.Substring(0, 1)); } } }
The output of the above program is as follows:
String is: Strings in C# Displaying first letter of each word S i C
A program that finds the index of a word in a string is given as follows:
Source Code: Program to find the index of a word in a string in C#
using System; public class Demo { public static void Main() { string[] str = new string[] { "Mango", "Apple", "Guava", "Orange", "Peach" }; Console.WriteLine("The given array is:"); for (int i = 0; i < str.Length; i++) { Console.WriteLine(str[i]); } int index = Array.IndexOf(str, "Peach"); Console.Write("The element Peach is found the index: "); Console.WriteLine(index); } }
The output of the above program is as follows:
The given array is: Mango Apple Guava Orange Peach The element Peach is found the index: 4
A program that lists all the substrings in a string is given as follows:
Source Code: Program to list all the substrings in a string in C#
using System; public class Demo { public static void Main() { string str = "boat"; Console.WriteLine("The substrings for boat are:"); for (int i = 1; i < str.Length; i++) { for (int j = 0; j <= str.Length - i; j++) { string substring = str.Substring(j, i); Console.WriteLine(substring); } } } }
The output of the above program is as follows:
The substrings for boat are: b o a t bo oa at boa oat
A program that splits a string on spaces is given as follows:
Source Code: Program to split a string on spaces in C#
using System; using System.Linq; using System.IO; class Example { static void Main() { string str = "Strings in C#"; Console.WriteLine("The original string is: " + str); string[] strSplit = str.Split(' '); Console.WriteLine("The splitted string is:"); foreach (string s in strSplit) { Console.WriteLine(s); } } }
The output of the above program is as follows:
The original string is: Strings in C# The splitted string is: Strings in C#
A program that matches all the digits in a string is given as follows:
Source Code: Program to match all the digits in a string in C#
using System; using System.Text.RegularExpressions; namespace Demo { class Example { private static void showMatch(string str, string exp) { Console.WriteLine("The Expression: " + exp); MatchCollection matchCol = Regex.Matches(str, exp); Console.WriteLine("The digits are:"); foreach (Match m in matchCol) { Console.WriteLine(m); } } static void Main(string[] args) { string str = "5 and 7 are prime numbers"; Console.WriteLine("Getting digits from a string"); Console.WriteLine("The string is: " + str); showMatch(str, @"\d+"); } } }
The output of the above program is as follows:
Getting digits from a string The string is: 5 and 7 are prime numbers The Expression: \d+ The digits are: 5 7
A program that removes the end part of a string is given as follows:
Source Code: Program to remove the end part of a string in C#
using System; using System.Text.RegularExpressions; namespace Example { class Example { static void Main(string[] args) { string str1 = "I love apples!"; string str2 = System.Text.RegularExpressions.Regex.Replace(str1, "!", "."); Console.WriteLine("str1: {0}", str1); Console.WriteLine("str2: {0}", str2); } } }
The output of the above program is as follows:
str1: I love apples! str2: I love apples.
A program that replaces parts of a string using Regex is given as follows:
Source Code: Program to replace parts of a string using Regex in C#
using System; using System.Text.RegularExpressions; namespace Demo { class Example { static void Main(string[] args) { string str1 = "Apples are red"; Console.WriteLine("Initial string: " + str1); string str2 = Regex.Replace(str1, "r.d", "green"); Console.WriteLine("Modified string: " + str2); } } }
The output of the above program is as follows:
Initial string: Apples are red Modified string: Apples are green
A program that removes duplicate characters from a string is given as follows:
Source Code: Program to remove duplicate characters from a string in C#
using System; using System.Linq; using System.Collections.Generic; namespace Demo { class Example { static void Main(string[] args) { string str = "ssskkyyy"; Console.WriteLine("Initial String: " + str); var newStr = new HashSet<char>(str); Console.Write("String after removing duplicates: "); foreach (char c in newStr) Console.Write(c); } } }
The output of the above program is as follows:
Initial String: ssskkyyy String after removing duplicates: sky
A program that removes white spaces from a string is given as follows:
Source Code: Program to remove white spaces from a string in C#
using System; using System.Text; class Demo { static void Main() { StringBuilder str = new StringBuilder("Edward Mason"); Console.WriteLine("Initial string: " + str.ToString()); str.Replace(" ", String.Empty); Console.WriteLine("String after removing white spaces: " + str.ToString()); } }
The output of the above program is as follows:
Initial string: Edward Mason String after removing white spaces: EdwardMason
using System; public class Demo { public static void Main() { string str; int c = 0, count = 1; str = "I love mangoes"; while (c <= str.Length - 1) { if(str[c]==' ' || str[c]=='\n' || str[c]=='\t') { count++; } c++; } Console.WriteLine("String: {0}", str); Console.WriteLine("Total words: {0}", count); } }
The output of the above program is as follows:
String: I love mangoes Total words: 3
A program that gets the first three letters from all strings is given as follows:
Source Code: Program that gets the first three letters from all strings in C#
using System; using System.Linq; using System.Collections.Generic; class Example { static void Main() { List<object> list = new List<object> { "John", "Mary", "Peter", "Susan", "Lucy" }; IEnumerable<string> result = list.AsQueryable() .Cast<string>() .Select(str => str.Substring(0, 3)); Console.WriteLine("First 3 letters from all strings are:"); foreach (string s in result) Console.WriteLine(s); } }
The output of the above program is as follows:
First 3 letters from all strings are: Joh Mar Pet Sus Luc
A program that splits a string into elements of a string is given as follows:
Source Code: Program that splits a string into elements of a string in C#
using System; class Example { static void Main() { string str = "The ocean is blue"; string[] elementStr = str.Split(' '); Console.WriteLine("String: " + str); Console.WriteLine("Separate elements of string:"); foreach (string word in elementStr) { Console.WriteLine(word); } } }
The output of the above program is as follows:
String: The ocean is blue Separate elements of string: The ocean is blue
A program that splits a string using regular expressions is given as follows:
Source Code: Program that splits a string using regular expressions in C#
using System; using System.Text.RegularExpressions; class Demo { static void Main() { string str = "The ocean is blue"; string[] result = Regex.Split(str, " "); Console.WriteLine("String: " + str); Console.WriteLine("Splitted string:"); foreach (string i in result) { Console.WriteLine(i); } } }
The output of the above program is as follows:
String: The ocean is blue Splitted string: The ocean is blue
A program that checks if a substring is present in a string is given as follows:
Source Code: Program that checks if a substring is present in a string in C#
using System; public class Demo { public static void Main() { string s1 = "Apple", s2 = "App"; bool flag; flag = s1.Contains(s2); if (flag) Console.Write("The substring " + s2 + " is in the string " + s1); else Console.Write("The substring " + s2 + " is not in the string " + s1); } }
The output of the above program is as follows:
The substring App is in the string Apple
A program that defines the multiline string literal is given as follows:
Source Code: Program that defines the multiline string literal in C#
using System; namespace Demo { class Example { static void Main(string[] args) { string str = @"Hello everyone, these are multiline strings in C#"; Console.WriteLine(str); } } }
The output of the above program is as follows:
Hello everyone, these are multiline strings in C#
A program that calculates the length of the string is given as follows:
Source Code: Program that calculates the length of the string in C#
using System; using System.Collections; namespace Demo { class Example { static void Main(string[] args) { string str = "It is raining"; Console.WriteLine("String: " + str); Console.WriteLine("String Length: " + str.Length); } } }
The output of the above program is as follows:
String: It is raining
A program that concatenates two strings is given as follows:
Source Code: Program that concatenates two strings in C#
using System; class Example { static void Main() { string str1 = "John"; string str2 = "Smith"; string strConcat = string.Concat(str1, str2); Console.WriteLine("str1: " + str1); Console.WriteLine("str2: " + str1); Console.WriteLine("Concatenated String: " + strConcat); } }
The output of the above program is as follows:
String: It is raining String Length: 13
A program that concatenates two strings is given as follows:
Source Code: Program that concatenates two strings in C#
using System; class Example { static void Main() { string str1 = "John"; string str2 = "Smith"; string strConcat = string.Concat(str1, str2); Console.WriteLine("str1: " + str1); Console.WriteLine("str2: " + str1); Console.WriteLine("Concatenated String: " + strConcat); } }
The output of the above program is as follows:
str1: John str2: John Concatenated String: JohnSmith
A program that shows the usage of the @ prefix on string literals is given as follows:
Source Code: Program that shows the usage of the @ prefix on string literals in C#
using System; namespace Demo { class Example { static void Main(string[] args) { string str = @"Hello User, The image is currently loading"; Console.WriteLine(str); } } }
The output of the above program is as follows:
Hello User, The image is currently loading
A program that checks if a string contains a special character is given as follows:
Source Code: Program that checks if a string contains a special character in C#
using System; namespace Demo { class myApplication { static void Main(string[] args) { string str = "String#@!"; char[] c1 = str.ToCharArray(); char[] c2 = new char[c1.Length]; int j = 0; for (int i = 0; i < c1.Length; i++) { if (!Char.IsLetterOrDigit(c1[i])) { c2[j] = c1[i]; j++; } } Array.Resize(ref c2, j); Console.WriteLine("String is: " + str); Console.WriteLine("Following are the special characters:"); foreach(var val in c2) { Console.WriteLine(val); } } } }
The output of the above program is as follows:
String is: String#@! Following are the special characters: # @ !
A program that checks if a string is palindrome or not is given as follows:
Source Code: Program that checks if a string is palindrome or not in C#
using System; namespace palindromeDemo { class Example { static void Main(string[] args) { string str, revStr; str = "madam"; char[] c = str.ToCharArray(); Array.Reverse(c); revStr = new string(c); bool b = str.Equals(revStr, StringComparison.OrdinalIgnoreCase); if (b == true) { Console.WriteLine(str + " is a palindrome"); } else { Console.WriteLine(str + " is not a palindrome"); } } } }
The output of the above program is as follows:
madam is a palindrome
A program that adds strings values to a list is given as follows:
Source Code: Program that adds strings values to a list in C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Demo { public class Example { public static void Main(String[] args) { List<string> strList = new List<string>(); strList.Add("Harry"); strList.Add("John"); strList.Add("Donald"); strList.Add("Mary"); strList.Add("Susan"); Console.WriteLine("Number of list values are: " + strList.Count); } } }
The output of the above program is as follows:
Number of list values are: 5
A program that counts the vowels in a string is given as follows:
Source Code: Program that counts the vowels in a string in C#
using System; public class Demo { public static void Main() { string str; int i, length, vCount = 0, cCount = 0; str = "Beautiful"; length = str.Length; for(i=0; i<length; i++) { if(str[i] =='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u' || str[i]=='A' || str[i]=='E' || str[i]=='I' || str[i]=='O' || str[i]=='U') { vCount++; } else { cCount++; } } Console.Write("Vowels in the string are: {0}", vCount); } }
The output of the above program is as follows:
Vowels in the string are: 5
A program that demonstrates the DataTime in C# is given as follows:
Source Code: Program that demonstrates the DataTime in C#
using System; static class Demo { static void Main() { DateTime dt = new DateTime(2015, 8, 2, 12, 4, 9, 123); Console.WriteLine(String.Format("{0:y yy yyy yyyy}", dt)); Console.WriteLine(String.Format("{0:M MM MMM MMMM}", dt)); Console.WriteLine(String.Format("{0:d dd ddd dddd}", dt)); } }
The output of the above program is as follows:
15 15 2015 2015 8 08 Aug August 2 02 Sun Sunday
A program that counts the upper and lower case characters in a string is given as follows:
Source Code: Program that counts the upper and lower case characters in a string in C#
using System; public class Demo { public static void Main() { string str = "Fish"; int i, len, lcount = 0, ucount = 0; Console.WriteLine("The String is: " + str); len = str.Length; for(i=0; i<len; i++) { if(str[i]>='a' && str[i]<='z') { lcount++; } else if(str[i]>='A' && str[i]<='Z') { ucount++; } } Console.WriteLine("Characters in lowercase: {0}", lcount); Console.WriteLine("Characters in uppercase: {0}", ucount); } }
The output of the above program is as follows:
The String is: Fish Characters in lowercase: 3 Characters in uppercase: 1
A program that reverses a string is given as follows:
Source Code: Program that reverses a string in C#
using System; namespace Demo { class Example { static void Main(string[] args) { string str = "Apple"; char[] c = str.ToCharArray(); Array.Reverse(c); Console.WriteLine("The string is: " + str); Console.Write("The reversed string is: "); foreach(var i in c) { Console.Write(i); } } } }
The output of the above program is as follows:
The string is: Apple The reversed string is: elppA
A program that replaces a word in a string is given as follows:
Source Code: Program that replaces a word in a string in C#
using System; public class Demo { public static void Main() { string str = "I love dancing"; Console.WriteLine("Original string: " + str); string newStr = str.Replace("dancing", "drawing"); Console.WriteLine("Edited string: " + newStr); } }
The output of the above program is as follows:
Original string: I love dancing Edited string: I love drawing
A program that sorts a string in C# is given as follows:
Source Code: Program that sorts a string in C#
using System; public class Example { public static void Main() { string[] str = { "John", "Sally", "Harry", "Peter", "Susan"}; Console.WriteLine("Initial values: "); foreach (string val in str) { Console.Write(val); Console.Write(" "); } Array.Sort(str); Console.WriteLine(); Console.WriteLine("Sorted values: "); foreach (string val in str) { Console.Write(val); Console.Write(" "); } } }
The output of the above program is as follows:
Initial values: John Sally Harry Peter Susan Sorted values: Harry John Peter Sally Susan
A program that finds the first 10 characters of a string in C# is given as follows:
Source Code: Program that finds the first 10 characters of a string in C#
using System; public class Demo { public static void Main() { string str = "Cricket is a famous sport"; string substr = str.Substring(0, 10); Console.WriteLine("String: " + str); Console.WriteLine("Substring: " + substr); } }
The output of the above program is as follows:
String: Cricket is a famous sport Substring: Cricket is
A program that finds the first character of a string in C# is given as follows:
Source Code: Program that finds the first character of a string in C#
using System; public class Demo { public static void Main() { string str = "Mangoes!"; string fChar = str.Substring(0, 1); Console.WriteLine("String: " + str); Console.WriteLine("First character: " + fChar); } }
The output of the above program is as follows:
String: Mangoes! First character: M
Avery good write-up. Please let me know what are the types of C# libraries used for AI development.
very satisfied!!
Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).
Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz
The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation
Leave a Reply
Your email address will not be published. Required fields are marked *