C# Programming · Lesson 3

Pulling Strings — Programming Examples

Five runnable C# examples covering trimming, casing, comparison, searching, splitting, and formatted string output.

  • strings
  • parsing
  • formatting
  • stringbuilder

Example 1 — Clean and Inspect a Course Code

This example shows that string methods return new strings. It trims a course code, changes its case, and inspects its length, first character, and a substring without changing the original value.

using System;

class Program
{
    static void Main()
    {
        string original = "  ist 2373  ";
        string cleaned = original.Trim();
        string upperCourse = cleaned.ToUpper();

        Console.WriteLine("Original: '" + original + "'");
        Console.WriteLine("Cleaned:  '" + cleaned + "'");
        Console.WriteLine("Upper:    '" + upperCourse + "'");
        Console.WriteLine("Length: " + cleaned.Length);
        Console.WriteLine("First character: " + cleaned[0]);
        Console.WriteLine("Department: " + cleaned.Substring(0, 3));
    }
}

Example 2 — Recognize Exit Commands

This example reads a command, removes extra spaces, and compares it with EXIT and QUIT without making letter case matter.

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a command: ");
        string command = Console.ReadLine() ?? "";
        command = command.Trim();

        if (String.Compare(command, "exit", true) == 0 ||
            String.Compare(command, "quit", true) == 0)
        {
            Console.WriteLine("The program will close.");
        }
        else
        {
            Console.WriteLine("You entered: " + command);
        }
    }
}

Example 3 — Search a Status Message

This example uses Contains(), IndexOf(), IndexOfAny(), and Substring() to answer different questions about the same status message.

using System;

class Program
{
    static void Main()
    {
        string message = "Build succeeded! Ready to run.";

        bool found = message.Contains("succeeded");
        int wordPosition = message.IndexOf("succeeded");

        char[] punctuationMarks = { '.', '!', '?' };
        int punctuationPosition = message.IndexOfAny(punctuationMarks);

        Console.WriteLine("Contains 'succeeded': " + found);
        Console.WriteLine("Word begins at index: " + wordPosition);
        Console.WriteLine("First punctuation is at index: " + punctuationPosition);

        if (wordPosition != -1)
        {
            string result = message.Substring(wordPosition, 9);
            Console.WriteLine("Matching text: " + result);
        }
    }
}

Example 4 — Add a Series of Numbers

This example splits one line of console input at commas and spaces, safely parses each usable segment with TryParse(), and totals the accepted integers.

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter whole numbers separated by commas or spaces: ");
        string input = Console.ReadLine() ?? "";

        char[] separators = { ',', ' ' };
        string[] segments = input.Split(separators);

        int sum = 0;

        foreach (string segment in segments)
        {
            string cleaned = segment.Trim();

            if (cleaned.Length > 0 &&
                Int32.TryParse(cleaned, out int number))
            {
                Console.WriteLine("Accepted: " + number);
                sum += number;
            }
        }

        Console.WriteLine("Sum: " + sum);
    }
}

Example 5 — Build a Formatted Enrollment Report

This example combines Trim(), PadRight(), numeric formatting, interpolation, and StringBuilder to assemble a small report efficiently.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string[] courses = { " IST 2373 ", "IST 1724", " IST 2224" };
        int[] seats = { 18, 7, 125 };

        StringBuilder report = new StringBuilder();
        report.Append("COURSE".PadRight(14));
        report.Append("SEATS\n");
        report.Append("--------------------\n");

        for (int i = 0; i < courses.Length; i++)
        {
            string course = courses[i].Trim();
            report.Append(course.PadRight(14));
            report.Append($"{seats[i]:N0}\n");
        }

        Console.WriteLine(report.ToString());
    }
}