404 Not Found

404 Not Found


nginx

Strings

Declaration and Initialization

string is an alias for System.String and is an immutable reference type. Once created, the content of a string cannot be changed.

Example

CSHARP
string name = "Hello";
string empty = "";
string nullStr = null;
string fromChar = new string('A', 5);
Console.WriteLine(name);
Console.WriteLine(fromChar);
▶ Try it Yourself
TEXT
Hello
AAAAA

String Immutability

Once a string object is created, its character sequence cannot be modified. All "modification" operations return a new string, leaving the original unchanged.

Example

CSHARP
string a = "Hello";
string b = a;
a = a + " World";
Console.WriteLine(a);
Console.WriteLine(b);
▶ Try it Yourself
TEXT
Hello World
Hello

Tip: b still points to the original "Hello", while a + " World" produces an entirely new string object.

String Concatenation

Use the + operator, String.Concat(), or String.Join() to combine multiple strings.

Example

CSHARP
string s1 = "Hello" + " " + "World";
string s2 = String.Concat("A", "B", "C");
string s3 = String.Join(", ", new string[] { "apple", "banana", "cherry" });
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
▶ Try it Yourself
TEXT
Hello World
ABC
apple, banana, cherry

String Interpolation

Use $"" interpolation syntax or String.Format() to embed variables within a string.

Example

CSHARP
string name = "Alice";
int age = 25;
string s1 = $"My name is {name}, age {age}.";
string s2 = String.Format("My name is {0}, age {1}.", name, age);
string s3 = $"2 + 3 = {2 + 3}";
Console.WriteLine(s1);
Console.WriteLine(s2);
Console.WriteLine(s3);
▶ Try it Yourself
TEXT
My name is Alice, age 25.
My name is Alice, age 25.
2 + 3 = 5

Tip: You can write any C# expression inside interpolation braces {}, and add format specifiers such as {value:F2}.

String Comparison

The == operator performs value equality comparison on strings (not reference comparison). Equals(), Compare(), and CompareOrdinal() offer more fine-grained control.

Example

CSHARP
string a = "hello";
string b = "hello";
string c = "HELLO";
Console.WriteLine(a == b);
Console.WriteLine(a.Equals(b));
Console.WriteLine(String.Compare(a, c, StringComparison.OrdinalIgnoreCase) == 0);
Console.WriteLine(String.CompareOrdinal(a, c) > 0);
▶ Try it Yourself
TEXT
True
True
True
True

Warning: String == compares values, not references, which differs from the behavior of most other reference types.

Common Methods: Length / Substring / Replace / Split

These are the most frequently used methods for everyday string operations.

Example

CSHARP
string s = "Hello, World!";
Console.WriteLine(s.Length);
Console.WriteLine(s.Substring(7));
Console.WriteLine(s.Substring(0, 5));
Console.WriteLine(s.Replace("World", "C#"));
string parts = "a,b,c";
foreach (string p in parts.Split(','))
{
    Console.WriteLine(p);
}
▶ Try it Yourself
TEXT
13
World!
Hello
Hello, C#!
a
b
c

Common Methods: Trim / Contains / Index

Trim() removes leading and trailing whitespace, Contains() checks for a substring, and IndexOf() / LastIndexOf() find positions.

Example

CSHARP
string s = "  Hello World  ";
Console.WriteLine($"[{s.Trim()}]");
Console.WriteLine(s.Contains("World"));
Console.WriteLine(s.IndexOf("World"));
Console.WriteLine(s.LastIndexOf("o"));
▶ Try it Yourself
TEXT
[Hello World]
True
8
7

Common Methods: Case / StartsWith / EndsWith / Pad / Remove / Insert

More practical string processing methods.

Example

CSHARP
string s = "Hello";
Console.WriteLine(s.ToUpper());
Console.WriteLine(s.ToLower());
Console.WriteLine(s.StartsWith("Hel"));
Console.WriteLine(s.EndsWith("llo"));
Console.WriteLine("5".PadLeft(3, '0'));
Console.WriteLine("5".PadRight(3, '0'));
string r = "Hello World".Remove(5);
Console.WriteLine(r);
string ins = "H World".Insert(1, "ello");
Console.WriteLine(ins);
▶ Try it Yourself
TEXT
HELLO
hello
True
True
005
500
Hello
Hello World

Verbatim Strings and Raw Strings

Verbatim strings @"" do not process escape sequences, making them ideal for file paths. C# 11 introduced raw string literals """ for multi-line content that requires no escaping.

Example

CSHARP
string path = @"C:\Users\Doc\file.txt";
string json = """
    {
        "name": "Alice",
        "age": 25
    }
    """;
Console.WriteLine(path);
Console.WriteLine(json.Trim());
▶ Try it Yourself
TEXT
C:\Users\Doc\file.txt
{
    "name": "Alice",
    "age": 25
}

Tip: In verbatim strings, a double quote is written as "". Raw string literals start and end with at least three quotation marks.

StringBuilder Overview

When concatenating strings repeatedly in a loop, string creates a new object each time, which hurts performance. StringBuilder operates on an internal buffer and produces the final string only once.

Example

CSHARP
using System.Text;

var sb = new StringBuilder();
for (int i = 0; i < 5; i++)
{
    sb.Append(i);
    sb.Append(" ");
}
Console.WriteLine(sb.ToString().Trim());
▶ Try it Yourself
TEXT
0 1 2 3 4

Tip: Prefer StringBuilder when concatenating many strings in a loop to significantly reduce memory allocations.

Character Encoding

C# strings use UTF-16 encoding. A char occupies 2 bytes (one UTF-16 code unit).

Example

CSHARP
char ch = 'A';
Console.WriteLine(ch);
Console.WriteLine((int)ch);
Console.WriteLine(sizeof(char));
▶ Try it Yourself
TEXT
A
65
2

❓ FAQ

Q Does string == compare references or values?
A Values. The == operator for strings has been overloaded to perform content equality comparison.
Q Why should I use StringBuilder for string concatenation in loops?
A Because string is immutable, each concatenation creates a new object. StringBuilder modifies a buffer and only generates the final string at the end.
Q What is the difference between a verbatim string @"" and a regular string?
A Verbatim strings do not process escape sequences (such as \n, \t); backslashes are preserved literally, making them ideal for file paths and regular expressions.
Q What happens if Substring goes out of range?
A It throws ArgumentOutOfRangeException. You should check the length before calling it.

📖 Summary

📝 Exercises

  1. Declare a string variable and use interpolation to output "My name is XXX, and I am XX years old."
  2. Write a program that takes a comma-separated string "a,b,c,d", splits it with Split, and prints each element on a separate line
  3. Trim the string " Hello World ", then replace "World" with "C#" and output the result
  4. Use StringBuilder to concatenate the numbers 1 through 100, one per line, and output the final string
  5. Define a Windows file path C:\Program Files\MyApp\config.json using a verbatim string and output it
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏