Learn/C#/8. Strings and a small project
Lesson 8 of 15
Sign in

C#, lesson 8

Strings and a small project

Names, commands and lines of input are all text, so you will use string constantly. One rule shapes everything: strings are immutable. Methods such as ToUpper or Replace never change the original string; they return a new one that you must store or use.

Looking inside a string

Careful: Substring(start, length) takes a length, not an end index. Ranges like s[2..5] use start and end, with the end excluded.

Changing and splitting

Compare strings with ==, or with string.Equals(a, b, StringComparison.OrdinalIgnoreCase) to ignore case.

2 exercises to try what you just read.

Exercise 1

Palindrome checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Receipt printer

Press Ctrl Enter or Check to test your code.

Characters

A char is one UTF-16 code unit. The char type has handy static tests:

Building strings efficiently

Joining with + inside a loop makes a brand-new string every time. For many pieces, use a StringBuilder from System.Text, a mutable buffer:

To reverse a string, turn it into a char[], reverse that, and build a new string: new string(text.Reverse().ToArray()) needs LINQ, while char[] a = text.ToCharArray(); Array.Reverse(a); new string(a) does not.

Interpolated strings can also align columns: $"{name,-8}{price,6:F2}" pads name to 8 characters on the left and price to 6 on the right.

Putting it together

The second exercise is a small project that uses reading input (lesson 3), loops (5), a method (6) and string tools from this lesson. Plan before you type: what do you read, what do you keep, and what do you print at the end?

Further reading

  • Strings and string literals
  • String class methods
  • StringBuilder

Read one line of text. Ignoring case and every character that is not a letter or digit, decide whether it reads the same forwards and backwards. Print Palindrome or Not a palindrome. A line with no letters or digits at all counts as a palindrome.

Sample input:

Sample output:

Each input line is a purchase in the form name,quantity,unit price, for example apple,3,0.50. Skip blank lines. For each purchase, print the name in upper case, x and the quantity, and the line total with two decimals, separated by single spaces. After all purchases, print the total number of items and the grand total. Use decimal for money.

Write a local function static string FormatLine(string name, int qty, decimal lineTotal) that builds one receipt line.

Sample input:

Sample output:

With no purchases at all, print just Items: 0 and Total: 0.00.

string word = "hello";
word.ToUpper();            // result thrown away; word is still "hello"
word = word.ToUpper();     // now "HELLO"
string s = "CSharp rocks";
Console.WriteLine(s.Length);              // 12
Console.WriteLine(s[0]);                  // C   (a char)
Console.WriteLine(s.IndexOf("rocks"));    // 7   (-1 if missing)
Console.WriteLine(s.Contains("Sharp"));   // True
Console.WriteLine(s.StartsWith("CS"));    // True
Console.WriteLine(s.Substring(7));        // rocks       (from index 7)
Console.WriteLine(s.Substring(0, 6));     // CSharp      (start, length)
Console.WriteLine(s[..6]);                // CSharp      (a range: up to index 6)
"  padded  ".Trim();                     // "padded"
"a-b-c".Replace("-", "+");               // "a+b+c"
"x,y,z".Split(',');                      // ["x", "y", "z"]
string.Join(" | ", words);               // words is ["a", "b"]: "a | b"
"7".PadLeft(3, '0');                     // "007"
string.IsNullOrWhiteSpace("   ");        // True
new string('-', 5);                      // "-----"
foreach (char c in "R2-D2")
{
    if (char.IsLetterOrDigit(c))
    {
        Console.Write(char.ToLower(c));   // r2d2
    }
}
using System.Text;

var sb = new StringBuilder();
for (int i = 1; i <= 3; i++)
{
    sb.Append(i).Append("! ");
}
Console.WriteLine(sb.ToString().TrimEnd());   // 1! 2! 3!
Was it a car or a cat I saw?
Palindrome
apple,3,0.50
bread,1,2.25
milk,2,1.10
APPLE x3 1.50
BREAD x1 2.25
MILK x2 2.20
Items: 6
Total: 5.95