Strings, Part I#
Enough with numbers for a while. Strings of characters are another important type in C#.
A string in C# is a sequence of characters. For C# to
recognize a literal sequence of characters, like hello, as a string, it
must be enclosed in quotes " to delimit the string: "hello".
Special cases are considered later in String Special Cases.
String Concatenation#
Because everything in C# is typed, C# can give a special meaning to
operators depending on the types involved,
as we saw with /.
We can operate on numbers with arithmetic operators, including +.
With strings + has a completely different meaning. Look at the example:
Console.WriteLine("never" + "ending");
The plus operation with strings means concatenate the strings: join them together end to end.
C# is even a bit smarter. If you use a + with a string, presumably you
are looking to produce a string, so even if the second operand to the + is
not a string, it is automatically converted to a string representation before
concatenating:
int x = 42;
string result;
result = "We get " + x;
Console.WriteLine(result);
You can chain concatenations. We could make a full sentence adding a period:
Console.WriteLine("We get " + x + ".");
Note to Python programmers: C# has no *
multiplication operator for strings.
Four Copies Exercise#
In a scratch program, declare and initialize a string variable. Write an expression that evaluates to four copies of the string, so it works no matter what value you gave your string.
Sum String Exercise#
In a scratch program, declare and initialize two int variables, x and y. Then write an expression whose
value is “x + y is 56”, except that 56 is replaced by the sum of x and y, and is not
a literal, but calculated from the actual values of variables x and y (which do not
need to add up to 56 specifically).
This has a trick to it.
Ints and Strings Added#
In a scratch program, start with:
int x = 2;
int y = 3;
Think what each expression prints. Write one predicted response at a time, then test it, and put the right answer beside your answer if you were wrong:
x + "??" + y;
x + y + "??";
(x * y + "??");
"??" + x * y;
"??" + x + y;
x + "??" * y;
Can you explain the ones you got wrong, after looking at the actual answer? Precedence and operation order is important.