Strings are one of the most important data types in any modern language including C#. In this article, you will learn how to work with strings in C#. The article discusses the String class, its methods and properties and how to use them.
The System.String data type represents a string in .NET. A string class in C# is an object of type System.String. The String class in C# represents a string.
The following code creates three strings with a name, number, and double values.
// String of characters System.String authorName = "Susheel Kumar"; // String made of an Integer System.String age = "33"; // String made of a double System.String numberString = "33.23";
Here is the complete example that shows how to use stings in C# and .NET.
using System; namespace CSharpStrings { class Program { static void Main(string[] args) { // Define .NET Strings // String of characters System.String authorName = "Susheel Kumar"; // String made of an Integer System.String age = "33"; // String made of a double System.String numberString = "33.23"; // Write to Console. Console.WriteLine("Name: {0}", authorName); Console.WriteLine("Age: {0}", age); Console.WriteLine("Number: {0}", numberString); Console.ReadKey(); } } }
Create a string
There are several ways to construct strings in C# and .NET. Create a string using a constructorCreate a string from a literalCreate a string using concatenationCreate a string using a property or a methodCreate a string using formatting Create a string using its constructor
The String class has several overloaded constructors that take an array of characters or bytes. The following code snippet creates a string from an array of characters.
char[] chars = { 'S', 'u', 's', 'h', 'e', 'e' , 'l'}; string name = new string(chars); Console.WriteLine(name);
Create a string from a literal
This is the most common ways to instantiate a string.
You simply define a string type variable and assign a text value to the variable by placing the text value without double quotes. You can put almost any type of characters within double quotes accept some special character limitations.
The following code snippet defines a string variable named firstName and then assigns text value Susheel to it.
string firstName; firstName = "Susheel";
Alternatively, we can assign the text value directly to the variable.
string firstName = "Susheel";
Here is a complete sample example of how to create strings using literals.
using System; namespace CSharpStrings { class Program { static void Main(string[] args) { string firstName = "Susheel"; string lastName = "Kumar"; string age = "26"; string numberString = "33.23"; Console.WriteLine("First Name: {0}", firstName); Console.WriteLine("Last Name: {0}", lastName); Console.WriteLine("Age: {0}", age); Console.WriteLine("Number: {0}", numberString); Console.ReadKey(); } } }
Create a string using concatenation
Sting concatenation operator (+) can be used to combine more than one string to create a single string. The following code snippet creates two strings. The first string adds a text Date and current date value from the DateTime object. The second string adds three strings and some hard coded text to create a larger string.
string nowDateTime = "Date: " + DateTime.Now.ToString("D"); string firstName = "Susheel"; string lastName = "Kumar"; string age = "26"; string authorDetails = firstName + " " + lastName + " is " + age + " years o ld."; Console.WriteLine(nowDateTime); Console.WriteLine(authorDetails);
Create a string using a property or a method
Some properties and methods of the String class returns a string object such as SubString method. The following code snippet takes one sentence string and finds the age within that string. The code returns 26.
string authorInfo = "Susheel Kumar is 26 years old."; int startPosition = sentence.IndexOf("is ") + 1; string age = authorInfo.Substring(startPosition +2, 2 ); Console.WriteLine("Age: " + age);
Create a string with Format
The String.Format method returns a string. The following code snippet creates a new string using the Format method.
string name = "Susheel Kumar"; int age = 26; string authorInfo = string.Format({0} is {1} years old.", name, age.ToString()); Console.WriteLine(authorInfo);
Create a string using ToString Method
The ToString method returns a string. We can apply ToString on pretty much any data type that can be converted to a string. The following code snippet converts an int data type to a string.
string name = "Susheel Kumar"; int age = 26; string authorInfo = string.Format({0} is {1} years old.", name, age.ToString()); Console.WriteLine(authorInfo);
Get all characters of a string using C#
A string is a collection of characters.
The following code snippet reads all characters of a string and displays on the console.
string nameString = "Susheel Kumar"; for (int counter = 0; counter <= nameString.Length - 1; counter++) Console.WriteLine(nameString[counter]);
Size of string
The Length property of the string class returns the number of characters in a string including white spaces.
The following code snippet returns the size of a string and displays on the console.
string nameString = "Susheel Kumar"; Console.WriteLine(nameString); Console.WriteLine("Size of string {0}", nameString.Length);
Number of characters in a string
We can use the string.Length property to get the number of characters of a string but it will also count an empty character. So, to find out the exact number of characters in a string, we need to remove the empty character occurrences from a string.
The following code snippet uses the Replace method to remove empty characters and then displays the non-empty characters of a string.
string name = "Susheel Kumar"; string name = "Susheel Kumar"; // Get size of string Console.WriteLine("Size of string: {0}", name.Length ); // Remove all empty characters string nameWithoutEmptyChar = name.Replace(" ", ""); // Size after empty characters are removed Console.WriteLine("Size of non empty char string: {0}", nameWithoutEmptyChar.Length); // Read and print all characters for (int counter = 0; counter <= nameWithoutEmptyChar.Length - 1; counter++) Console.WriteLine(nameWithoutEmptyChar[counter]);
Convert String to Char Array
ToCharArray method converts a string to an array of Unicode characters. The following code snippet converts a string to char array and displays them.
string sentence = "Susheel Kumar is an author and developer in CoderArts"; char[] charArr = sentence.ToCharArray(); foreach (char ch in charArr) { Console.WriteLine(ch); }
Empty String
An empty string is a valid instance of a System.String object that contains zero characters. There are two ways to create an empty string. We can either use the string.Empty property or we can simply assign a text value with no text in it.
The following code snippet creates two empty strings.
string empStr = string.Empty; string empStr2 = "";
Both of the statements above generates the same output.
An empty string is sometimes used to compare the value of other strings. The following code snippet uses an empty string to compare with the name string.
string name = "Susheel Kumar"; if (name != empStr) { Console.WriteLine(name); }
In real-world coding, we will probably never create an empty string unless you plan to use it somewhere else as a non-empty string. We can simply use the string.Empty direct to compare a string with an empty string.
if (name != string.Empty) { Console.WriteLine(name); }
Here is a complete example of using an empty string.
string empStr = string.Empty; string empStr2 = ""; string name = "Susheel Kumar"; if (name != empStr) { Console.WriteLine(name); } if (name != string.Empty) { Console.WriteLine(name); }
Null String
A null string is a string variable that has not been initialized yet and has a null value. If you try to call any methods or properties of a null string, you will get an exception. A null string valuable is exactly the same as any other variable defined in your code.
A null string is typically used in string concatenation and comparison operations with other strings.
The following code example shows how to use a null string.
string nullStr = null; string empStr = string.Empty; string name = "Susheel Kumar"; if ((name != nullStr) || (name != empStr)) { Console.WriteLine(name + " is neither null nor empty"); }
I took the computer science course but I was not good with it so that is the reason I found someone whom I can pay for essay writing. He was able to provide me viable solutions to my problem.
Yes ,share your
I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot! patriotchimneysweeps.com
I am overwhelmed by your post with such a nice topic. Usually I visit your blogs and get updated through the information you include but today’s blog would be the most appreciable. Well done! https://www.bigsoftyscookies.com/product-page/oatmeal-chocolate-chip
Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing. https://www.dhuc.org/property-perservation.html
this blog was really great, never seen a great blog like this before. i think im gonna share this to my friends.. videographers near me
I am impressed by the information that you have on this blog. It shows how well you understand this subject. magicien close-up Bordeaux
Bikesfamily.com is a professional B2B trading platform operated by Joy Kie Co.ltd. With the participation of multiple suppliers . Bikesfamily.com has different types of bicycle related products, including bicycles (Kids Bike , MTB , Road Bike, City Bike , etc.). By partnering with Bikesfamily.com, you can access Joy Kie’s strengths and expertise in bicycle products and services. Bikesfamily.com upholds the mission of "making international trade easier" and aims to become the world's largest integrated B2B online vertical trading platform for bicycles and bicycle-related products. E-Skateboards supplier
Truly, this article is really one of the very best in the history of articles. I am a antique ’Article’ collector and I sometimes read some new articles if I find them interesting. And I found this one pretty fascinating and it should go into my collection. Very good work! gate valve
A+网课™的各类专业共计1000+精英Tutor团队可以为你完成整个、几周或一周网课,包括所有课后的Assignment、Essay、Project、Quiz、Exam、Report等。我们保证你可以实时跟Tutor直接互动、保证90/100分、100%准时。高质服务,合理价格,满意付款 加拿大网课代修
This was incredibly an exquisite implementation of your ideas Visit Website
I would recommend my profile is important to me, I invite you to discuss this topic... Visit Website
I think it could be more general if you get a football sports activity Visit Website
Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing. Visit Website
Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post. Visit Website
Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Visit Website
Super site! I am Loving it!! Will return once more, Im taking your food likewise, Thanks. Visit Website
Hey, great blog, but I don’t understand how to add your site in my rss reader. Can you Help me please? Visit Website
Always so interesting to visit your site.What a great info, thank you for sharing. this will help me so much in my learning Visit Website
I don t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for a great site. Visit Website
Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job! Visit Website