Data Types
Strings and Chars
A string stores text, while a char stores one character.
string
A string is a sequence of characters.
Strings and Chars
StringsChars.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
string word = "code";
char first = word[0];
int length = word.Length;
Console.WriteLine($"word={word}");
Console.WriteLine($"first={first}");
Console.WriteLine($"length={length}");
}
}
using System;
class Program
{
static void Main()
{
string word = "data";
char first = word[0];
int length = word.Length;
Console.WriteLine($"word={word}");
Console.WriteLine($"first={first}");
Console.WriteLine($"length={length}");
}
}
using System;
class Program
{
static void Main()
{
string word = "trace";
char first = word[0];
int length = word.Length;
Console.WriteLine($"word={word}");
Console.WriteLine($"first={first}");
Console.WriteLine($"length={length}");
}
}
word ← code, first ← c, length ← 4
4{5 static void Main()6 {7 string word→ code = "code"; //@word="data", "trace"8 char first→ c = word[0]c;9 int length→ 4 = word.Length4;1011 Console.WriteLine($"word={wordcode}");12 Console.WriteLine($"first={firstc}");13 Console.WriteLine($"length={length4}");14 }outputword=code first=c length=4
word ← data, first ← d, length ← 4
4{5 static void Main()6 {7 string word→ data = "data";8 char first→ d = word[0]d;9 int length→ 4 = word.Length4;1011 Console.WriteLine($"word={worddata}");12 Console.WriteLine($"first={firstd}");13 Console.WriteLine($"length={length4}");14 }outputword=data first=d length=4
word ← trace, first ← t, length ← 5
4{5 static void Main()6 {7 string word→ trace = "trace";8 char first→ t = word[0]t;9 int length→ 5 = word.Length5;1011 Console.WriteLine($"word={wordtrace}");12 Console.WriteLine($"first={firstt}");13 Console.WriteLine($"length={length5}");14 }outputword=trace first=t length=5
Follow the Text
wordstarts ascode.first = word[0]readsc.length = word.Lengthis4.- The program prints
word=code,first=c, andlength=4. | word | first | length | | --- | --- | --- | | code | c | 4 | | data | d | 4 | | trace | t | 5 |
Exercise: StringsChars.cs
Reproduce first=c and length=4, then use words data and trace to predict each first character and length.