C# Strings

Learn via video courses
Topics Covered

Overview

In C#, strings are sequences of characters used to store and manipulate text data. They are immutable, meaning once created, their content cannot be changed. Strings are essential for tasks like text processing, data input/output, and more.

Accessing individual characters or substrings in C# is straightforward with indexing and the Substring() method. Strings in C# support Unicode characters, making them suitable for internationalization and localization. C# also provides built-in support for regular expressions to perform complex text pattern matching and manipulation.

Example of C# Strings

Create a Variable of Type String and Assign it a Value

Output

In the above code, we declare a string variable named greeting and assign it the value "Hello, World!". The string variable can now hold and display the text "Hello, World!" in our C# program.

By declaring and initializing a string variable, we can store and manipulate text-based data in our C# programs. The assigned value can be modified or accessed as needed throughout the program.

Executing the code will output "Hello, World!" to the console. This example demonstrates the basic syntax and functionality of creating and assigning a value to a string variable in C#.

String Characteristics

In C#, strings possess several important characteristics that make them a versatile data type for handling text-based information. Here are some key characteristics of C# strings:

  • Immutable:

    Once a string is created, it cannot be changed. Any operation that appears to modify a string creates a new string with the modified content.

  • Sequential Access:

    Strings allow sequential access to individual characters, making it possible to iterate over each character in a string.

  • Length:

    Strings have a property called Length that returns the number of characters in the string.

  • Unicode Support:

    C# strings support Unicode characters, enabling the representation of a wide range of international characters and symbols.

  • Escape Sequences:

    Strings can include special escape sequences to represent characters that are difficult to type directly, such as newline (\n) or tab (\t).

Understanding these characteristics will help you effectively manipulate and utilize strings in your C# programs.

Differences Between String and System.String

In C#, the terms "string" and "System.String" are often used interchangeably to refer to the same data type. However, there is a subtle difference between the two:

stringSystem.String
Alias for System.StringFully qualified name of the class
Used interchangeably with "string"Used interchangeably with "System.String"
Convenient shorthand notationOfficial name in the .NET Framework
Accessible in any C# programPart of the .NET Framework's base class library
Represents a sequence of charactersRepresents a sequence of characters
Provides various methods and propertiesProvides various methods and properties for string manipulation

In practical terms, both "string" and "System.String" can be used to declare and work with strings in C#. It's primarily a matter of personal preference and coding style.

Different Ways for Creating a String

There are various ways to create a string, which are discussed below.

From Literal

One of the simplest ways to create a string in C# is by using a string literal. A string literal is a sequence of characters enclosed within double quotation marks. Here's an example using the full working code template:

Output

In the above code, we declare a string variable named literalString and assign it the value "This is a string literal." We then use Console.WriteLine() to output the value of literalString to the console.

By using string literals, you can easily assign specific textual content to a string variable for immediate use in your program.

Using Concatenation

Another way to create a string is by combining multiple strings using the concatenation operator (+). Here's an example using the full working code template.

Output

In this example, we declare two string variables named firstName and lastName and assign them the values "John" and "Doe", respectively. We then concatenate the two strings together, adding a space in between, to create the fullName string. Finally, we use Console.WriteLine() to output the value of fullName to the console.

Concatenation allows you to combine different strings or variables to dynamically build a string that meets your specific requirements.

These examples illustrate different methods of creating strings in C#, showcasing practical working code that you can use and modify in your programs.

Using a Constructor

You can create a string using the String class constructor. The constructor takes a character array or another string as a parameter. Here's an example using the full working code template.

Output

In the above code, we create a character array charArray with the letters 'H', 'e', 'l', 'l', and 'o'. Then, we use the new string(charArray) constructor to create a new string constructedString from the character array. Finally, we output the value of constructedString to the console.

Using a Property or a Method

C# provides various properties and methods to create strings dynamically. For example, you can use the String.Join() method to concatenate an array of strings into a single string. Here's an example.

Output

In this code, we have an array of strings containing "Hello" and "World". By using String.Join(), we concatenate the strings in the array, separating them with a space, and store the result in the joinedString variable. Finally, we display the value of joinedString on the console.

Using formatting

C# provides string formatting options to create formatted strings. You can use the String.Format() method or string interpolation to accomplish this. Here's an example using string interpolation.

Output

In this code, we declare a string variable name with the value "John" and an integer variable age with the value 30. Using string interpolation, denoted by the $ symbol, we create a formatted string formattedString that includes the values of name and age. Finally, we display the formatted string on the console.

These examples demonstrate different ways to create strings in C#, showcasing practical working code that you can use and modify based on your specific needs and preferences.

String Length

The length of the string in C# refers to the number of characters it contains. The length can be obtained using the Length property of the string. Here's an example:

Output

In the above code, we declare a string variable named message with the value "Hello, World!". We then use the Length property to retrieve the length of the string and store it in the integer variable length. Finally, we output the length using string interpolation to display the result on the console.

Understanding the length of a string is crucial for performing various operations, such as extracting substrings, iterating over characters, or validating input constraints. By utilizing the Length property, you can access and work with the number of characters within a string in your C# programs.

C# String Methods

C# provides a rich set of built-in methods that allow you to manipulate and perform operations on strings. These methods are part of the String class and offer various functionalities. Here are a few commonly used string methods:

  • ToUpper() and ToLower():

    These methods convert a string to uppercase or lowercase, respectively.

  • Substring():

    This method extracts a substring from a string based on a specified starting index and length.

  • Replace():

    This method replaces all occurrences of a specified substring with another substring.

  • Split():

    This method splits a string into an array of substrings based on a specified delimiter.

  • Trim(), TrimStart(), and TrimEnd():

    These methods remove leading and trailing whitespace characters from a string.

  • Contains():

    This method checks if a specific substring exists within a string.

  • IndexOf() and LastIndexOf():

    These methods return the index of the first or last occurrence of a substring within a string.

  • StartsWith() and EndsWith():

    These methods check if a string starts or ends with a specific substring.

  • Concat():

    This method concatenates multiple strings together.

These are just a few examples of the many string methods available in C#. By utilizing these methods, you can efficiently manipulate, transform, and extract information from strings in your C# programs.

C# String Interpolation

C# string interpolation is a convenient feature that allows you to embed expressions directly within a string. It simplifies the process of combining variables or expressions with static text. String interpolation uses the $ symbol followed by curly braces {} to enclose the expressions within the string.

Here's an example:

Output

In the above code, we declare a string variable name with the value "John" and an integer variable age with the value 30. We then use string interpolation to embed the values of name and age within the message string. The resulting message will be "My name is John and I am 30 years old." Finally, we display the message on the console.

String interpolation offers a more readable and concise way to construct strings, especially when incorporating dynamic values or expressions. It eliminates the need for explicit concatenation or formatting, resulting in cleaner and more maintainable code.

C# Special Characters

In C#, special characters are used to represent non-printable or difficult-to-type characters within strings. These characters are typically preceded by a backslash (\) to indicate their special meaning. Here are some commonly used special characters in C#:

\n: Represents a newline character.

\t: Represents a tab character.

": Represents a double quotation mark.

': Represents a single quotation mark.

\: Represents a backslash.

\r: Represents a carriage return.

\b: Represents a backspace.

\f: Represents a form feed.

\uXXXX: Represents a Unicode character based on its hexadecimal value.

Here's an example that demonstrates the usage of special characters:

Output

In the above code, the message string contains special characters. \t represents a tab character, and \n represents a newline character. When the string is printed to the console, the tab character will create a horizontal tab space, and the newline character will cause a line break. By utilizing special characters, you can add formatting and structure to your strings, making them more expressive and readable. These characters provide a way to represent non-visible or control characters within your C# string literals.

Conclusion

  • C# strings are fundamental data types used for representing and manipulating textual information in programming.
  • Strings in C# are immutable, meaning they cannot be changed once created.
  • Reading user input in C# is achieved using the Console.ReadLine() method.
  • Different ways to create strings in C# include using literals, concatenation, constructors, properties/methods, and formatting.
  • String methods such as ToUpper(), Substring(), Replace(), and Split() provide powerful capabilities for manipulating string data.