In this tutorial, we will learn about strings in C#. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in C# is an object of the System.String
class. Strings are immutable, meaning their value cannot be changed once created. Strings are used for storing and handling text data.
Strings can be created in C# using the string
keyword:
string str = "Hello, world!";
Strings can also be created using the String
class:
String str = "Hello, world!";
Console.WriteLine
.using System;
class Program {
static void Main() {
string str = "Hello, world!";
Console.WriteLine(str);
}
}
Hello, world!
using System;
class Program {
static void Main() {
string str = "Hello";
Console.WriteLine(str[0]); // Accessing using array indexing
Console.WriteLine(str[1]);
}
}
H e
using System;
class Program {
static void Main() {
string str = "Hello";
str = 'J' + str.Substring(1); // Modifying individual character
str += " World!"; // Appending new characters
Console.WriteLine(str);
}
}
Jello World!
+
operator or the String.Concat
method.using System;
class Program {
static void Main() {
string str1 = "Hello";
string str2 = " World!";
string str3 = str1 + str2; // Concatenating strings
Console.WriteLine(str3);
}
}
Hello World!
IndexOf
method to find a substring.using System;
class Program {
static void Main() {
string str = "Hello, world!";
int pos = str.IndexOf("world"); // Finding substring
if (pos != -1) {
Console.WriteLine("Found 'world' at position: " + pos);
} else {
Console.WriteLine("Substring not found");
}
}
}
Found 'world' at position: 7
Length
property to get the length of the string.using System;
class Program {
static void Main() {
string str = "Hello, world!";
Console.WriteLine("Length of the string: " + str.Length); // Getting string length
}
}
Length of the string: 13