
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Arithmetic Operators
- C# - Assignment Operators
- C# - Relational Operators
- C# - Logical Operators
- C# - Bitwise Operators
- C# - Miscellaneous Operators
- C# - Operators Precedence
- C# Conditional Statements
- C# - Decision Making
- C# - If
- C# - If Else
- C# - Nested If
- C# - Switch
- C# - Nested Switch
- C# Control Statements
- C# - Loops
- C# - For Loop
- C# - While Loop
- C# - Do While Loop
- C# - Nested Loops
- C# - Break
- C# - Continue
- C# OOP & Data Handling
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
C# - Strings
In C#, you can use strings as array of characters, However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for the System.String class.
Creating a String Object
You can create a string object using one of the following methods −
By assigning a string literal to a String variable
By using a String class constructor
By using the string concatenation operator (+)
By retrieving a property or calling a method that returns a string
By calling a formatting method to convert a value or an object to its string representation
Example to Create a String Object
The following example demonstrates all the methods listed above:
using System; namespace StringApplication { class Program { static void Main(string[] args) { // Creating a string using a string literal and concatenation string fname, lname; fname = "Rowan"; lname = "Atkinson"; char[] letters = {'H', 'e', 'l', 'l', 'o'}; string[] sarray = { "Hello", "From", "Tutorials", "Point" }; string fullname = fname + " " + lname; Console.WriteLine("Full Name: {0}", fullname); // Creating a string using a character array string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); // Joining an array of strings string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); // Formatting method to convert a value DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); } } }
When the above code is compiled and executed, it produces the following result −
Full Name: Rowan Atkinson Greetings: Hello Message: Hello From Tutorials Point Message: Message sent at 5:58 PM on Wednesday, October 10, 2012
Creating a String
You can create a string in C# using string literals or the String class.
Example
In the following example, we are creating a simple string and printing it.
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string message = "Hello, C#!"; Console.WriteLine(message); } } }
When the above code is compiled and executed, it produces the following result −
Hello, C#!
Finding String Length
You can find the length of a string using the Length
property.
Example
In the following example, we are finding and printing the length of a given string.
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "C# Programming"; int length = str.Length; Console.WriteLine("Length of the string: " + length); } } }
When the above code is compiled and executed, it produces the following result −
Length of the string: 14
Iterate Over String Characters
You can iterate over each character in a string using a foreach
loop.
Example
In the following example, we are iterating through each character of a string and printing them separately.
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "C# by TP"; foreach (char ch in str) { Console.WriteLine(ch); } } } }
When the above code is compiled and executed, it produces the following result −
C # b y T P
Comparing Strings
You can compare two strings using the String.Compare
method or the equality operator.
Example
In the following example, we are comparing two strings and displaying whether they are equal or not.
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str1 = "Hello"; string str2 = "World"; if (String.Compare(str1, str2) == 0) { Console.WriteLine("Strings are equal."); } else { Console.WriteLine("Strings are not equal."); } } } }
When the above code is compiled and executed, it produces the following result −
Strings are not equal.
Checking for a Substring
You can check if a string contains another string using the Contains
method.
Example
In the following example, we are checking if a given substring exists in a string.
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "Welcome to C# programming"; if (str.Contains("C#")) { Console.WriteLine("The sequence 'C#' was found."); } } } }
When the above code is compiled and executed, it produces the following result −
The sequence 'C#' was found.
Getting a Substring
You can extract a part of a string using the Substring
method.
Example
In the following example, we are extracting a part of a string and displaying it:
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str = "C# Programming Language"; Console.WriteLine(str); string substr = str.Substring(3, 11); Console.WriteLine(substr); } } }
When the above code is compiled and executed, it produces the following result −
Programming
Joining Strings
You can join multiple strings using the String.Join
method.
Example
In the following example, we are joining an array of strings using a newline character:
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string[] lines = new string[] { "C# is a modern", "Object-oriented", "Programming language" }; string result = String.Join("\n", lines); Console.WriteLine(result); } } }
When the above code is compiled and executed, it produces the following result −
C# is a modern Object-oriented Programming language
Handling Strings Using StringBuilder
StringBuilder helps to modify strings because regular strings cannot be changed directly. You can use StringBuilder
to add, insert, or replace text without creating new string copies.
Example: Using StringBuilder
The following example demonstrates how to use StringBuilder
to modify strings:
using System; using System.Text; class Program { static void Main() { StringBuilder sb = new StringBuilder("Hello"); sb.Append(" World!"); sb.Insert(6, "C# "); sb.Replace("World", "Everyone"); Console.WriteLine(sb.ToString()); } }
When executed, this program outputs:
Hello C# Everyone!
Properties of the String Class
The String class has the following two properties −
Sr.No. | Property & Description |
---|---|
1 |
Chars Gets the Char object at a specified position in the current String object. |
2 |
Length Gets the number of characters in the current String object. |
Methods of the String Class
The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods −
Sr.No. | Methods & Description |
---|---|
1 |
Clone()
It returns a reference to this instance of the String. |
2 |
CompareOrdinal()
It compares two strings by evaluating the numeric values of the corresponding characters in the strings. |
3 |
Compare()
It compares two specified String objects using the specified rules (case sensitivity, culture-specific, etc.). |
4 |
Concat()
It concatenates two string objects. |
5 |
Contains()
It returns a value indicating whether the specified String object occurs within this string. |
6 |
CopyTo()
It copies a specified number of characters from this string to a specified position in a character array. |
7 |
EndsWith()
It determines whether the end of this string instance matches the specified string. |
8 |
Equals()
It determines whether two specified String objects have the same value. |
9 |
Format()
It replaces format items in a string with the string representation of the corresponding objects. |
10 |
GetEnumerator()
It retrieves an enumerator that can iterate through the individual characters in this string. |
11 |
GetHashCode()
It returns the hash code for this string. |
12 |
IndexOfAny()
It finds the index of the first occurrence of any character in a specified array of characters. |
13 |
IndexOf()
It reports the zero-based index of the first occurrence of a specified substring within this string. |
14 |
Insert()
It inserts a string at a specified index in the current string. |
15 |
IsNullOrEmpty()
It checks if the string is either null or empty. |
16 |
IsNullOrWhiteSpace()
It checks if the string is null, empty, or consists only of white-space characters. |
17 |
Join()
It concatenates the string representations of an array of objects, with a specified separator.. |
18 |
LastIndexOf()
It reports the zero-based index of the last occurrence of a specified substring within the string. |
19 |
PadLeft()
It pads the string on the left with a specified character to achieve a given total length. |
20 |
PadRight()
It pads the string on the right with a specified character to achieve a given total length. |
21 |
Remove()
It removes a specified number of characters from the current string, starting at a given position. |
22 |
Replace()
It replaces all occurrences of a specified substring with another substring. |
23 |
Split()
It splits a string into substrings based on specified delimiters. |
24 |
StartWith()
It determines whether the beginning of this string instance matches the specified string. |
25 |
Substring()
It retrieves a substring starting at a specified index, continuing to the end of the string. |
26 |
ToCharArray()
It converts the string to a character array. |
27 |
ToLower()
It converts all characters of the string to lowercase. |
28 |
ToString()
It returns a string representation of the object. |
29 |
ToUpper()
It converts all characters of the string to uppercase. |
30 |
TrimEnd()
It removes all trailing white-space characters from the current string. |
31 |
TrimStart()
It removes all leading white-space characters from the current string. |
32 |
Trim()
It removes all leading and trailing white-space characters from the current string. |
In this chapter, we have summarized key methods of the string class commonly used in C# programming. For the complete list of methods and String class constructors, visit the MSDN library.