Strings as Arrays
A string behaves as a read-only array of characters.
string message = "wow hello";
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| character | w | o | w | ' ' | h | e | l | l | o |
Reading Characters
Use square brackets and zero-based indexing, just like an array. Each element is a char.
Console.WriteLine($"{message[0]} {message[1]} {message[2]}"); // 0-8 indices
We can use Length as well! Valid indices run from 0 to Length - 1. Anything outside that throws IndexOutOfRangeException.
Console.WriteLine(message.Length); // 9 items
Strings Are Immutable
You can read characters, but you can't assign them:
message[0] = "c"; // ❌ Error: read only
To "change" a string, you build a new one:
char[] newMessage = new char[message.Length];
for(int i=0; i<newMessage.Length; i++)
{
newMessage[i] = message[i];
}
newMessage[0] = 'c'; // single quotations for characters btw
Converting to Strings
Since strings are just an array of characters, the array creation syntax actually works here as well :)
string finalMessage = new string(newMessage); // round brackets this time tho
string vs char[]
string | char[] | |
|---|---|---|
| Mutable? (can be modified) | ❌ | ✅ |
works with index / Length? | ✅ | ✅ |