Skip to main content

Strings as Arrays

A string behaves as a read-only array of characters.

string message = "wow hello";
index012345678
characterwow' 'hello

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[]​

stringchar[]
Mutable? (can be modified)❌✅
works with index / Length?✅✅