Codiqo

Learn C# · lesson 6 of 61 · about 6 minutes

Strings

Give your hero a title and draw a health bar: join, measure and index strings, and repeat a character.

What you'll learn

  • Join strings with +
  • Read Length and single characters
  • Build a string from a repeated character

Working with text

A string is text. Some things you can do with one:

  • hero + " the Brave" joins two strings
  • hero.Length is how many characters it has
  • hero[0] is the character at position 0, a char: positions start at 0
  • new string('#', 6) repeats one character: ######
  • "Ada" == "ada" compares text, and capitals count, so it's False

A string can't be changed once it's made: hero[0] = 'E'; won't compile. To change it, make a new one.

A hero's title

string hero = "Ada";
string title = hero + " the Brave";
Console.WriteLine(title);
Console.WriteLine($"{hero.Length} letters, starts with {hero[0]}");
Console.WriteLine(new string('#', 6));

Output

Ada the Brave
3 letters, starts with A
######

A health bar

Games show health as a bar. With one # for every 5 HP, the bar is new string('#', heroHp / 5). That's integer division from unit 1: 4 HP gives 4 / 5 = 0 marks, an empty bar.

Two health bars

int heroHp = 30;
int slimeHp = 4;
Console.WriteLine($"Ada   [{new string('#', heroHp / 5)}]");
Console.WriteLine($"Slime [{new string('#', slimeHp / 5)}]");

Output

Ada   [######]
Slime []

Tip

+ works from left to right: "Lv " + 1 + 2 is Lv 12, because the 1 is joined to the text before the 2 arrives. Brackets make the numbers add first.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.