Working with Strings

String manipulation is very important especially in console applications. In this section, you will learn about how to manipulate strings.

String Concatenation

String concatenation in C# is the process of combining two or more strings to create a new string. In C#, you can concatenate strings using various techniques, each with its advantages and use cases.

Using the `+` Operator

At the start, this method will probably make the most sense. As you get further along, you will start to realize it is very unintuitive. Nonetheless, it is important to know as for some scenarios, it is the only option. Here is an example..

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
// returns: John Doe

String Interpolation

String interpolation is a more modern and readable way to concatenate strings in C#. It allows you to embed expressions within a string literal using the $ symbol, and the expressions are evaluated and inserted into the resulting string.

string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";
// returns: John Doe

String Concat method

I mean....sure

string firstName = "John";
string lastName = "Doe";
string fullName = string.Concat(firstName, " ", lastName);
// returns: John Doe

As you can see, there are a lot of ways to combine strings and add variables. It is personal preference. I prefer the middle method personally.

Other methods

C# provides a lot of methods for strings. I am not going to go in depth in all of the methods as that would take too long. I would recommend looking at this site that has most of the important methods. -> Code Maze

Providing more information to the user

Let's make it where when the balance changes, we provide a better explanation of what happened.

static void Main(string[] args)
{
    string name = "John Doe";
    int age = 13;
    double balance = 500.00;
    balance = DepositBalance(balance, 250);
    balance = WithdrawBalance(balance, 1000);
}
static double WithdrawBalance(double balance, double balanceToSubtract)
{
    Console.WriteLine($"Withdrew {balanceToSubtract}.");
    return balance - balanceToSubtract;
}

static double DepositBalance(double balance, double additionalBalance)
{
    if (Balance - additionalBalance < 0)
    {   
        Console.WriteLine($"Funds insufficient\nMax Funds that can be deposited: {Balance}");
        return Balance;
    }
    Console.WriteLine($"Deposited {additionalBalance}.");
    return balance + additionalBalance;
}

Using string interpolation, we can now give the users more information about what is happening when trying to deposit and withdraw money. Now, it returns the below when the user tries to withdraw more than they can.

Funds insufficient
Max Funds that can be deposited: {Insert whatever the person's balance is}

Next Section: Control Flow