Strings, Bool, If..Else, Switch, Loops, Break/Continue Flashcards
A string is a sequence of characters used to represent text. It is one of the most commonly used data types for working with textual data.
What are some key characteristics of a string.
- Immutable:
Strings in C# are immutable, meaning once a string is created, it cannot be changed. Any operation that modifies a string will create a new string object with the modified value, rather than altering the original string.
Example:
string str = “Hello”;
str = str + “ World”; // A new string is created; original ‘str’ is unchanged.
- Reference Type:
Although a string represents a sequence of characters, it behaves as a reference type. This means when you assign one string to another, both variables reference the same string in memory.
Example:
string str1 = “Hello”;
string str2 = str1; // str1 and str2 now point to the same string in memory.
- String Length:
The length of a string can be accessed using the Length property, which returns the number of characters in the string.
Example:
string str = “Hello”;
Console.WriteLine(str.Length); // Output: 5
- String Indexing:
Strings in C# are zero-indexed, meaning the first character of the string is at index 0, the second character is at index 1, and so on.
Example:
string str = “Hello”;
char firstChar = str[0]; // ‘H’
char secondChar = str[1]; // ‘e’
- Escape Sequences:
Strings can contain special characters using escape sequences, which are preceded by a backslash (). Common escape sequences include:
\n – Newline
\t – Tab
\ – Backslash
" – Double quote
Example:
string text = “Hello\nWorld”; // Creates a newline between “Hello” and “World”
Console.WriteLine(text);
- String Concatenation:
You can combine strings using the + operator or string interpolation (introduced in C# 6) using $”…”.
Example:
string str1 = “Hello”;
string str2 = “World”;
string result = str1 + “ “ + str2; // Using concatenation
string interpolated = $”{str1} {str2}”; // Using string interpolation
Console.WriteLine(result); // Output: Hello World
- String Methods: C# provides many built-in methods for working with strings. Here are some common ones:
ToUpper(): Converts all characters in a string to uppercase.
string str = “hello”;
Console.WriteLine(str.ToUpper()); // Output: HELLO
ToLower(): Converts all characters in a string to lowercase.
string str = “HELLO”;
Console.WriteLine(str.ToLower()); // Output: hello
Substring(): Extracts a substring from the string.
string str = “Hello World”;
string sub = str.Substring(0, 5); // Extracts “Hello”
Console.WriteLine(sub); // Output: Hello
Contains(): Checks if the string contains a specific substring.
string str = “Hello World”;
bool contains = str.Contains(“World”); // Returns true
Console.WriteLine(contains); // Output: True
Replace(): Replaces occurrences of a substring with a new substring.
string str = “Hello World”;
string newStr = str.Replace(“World”, “C#”);
Console.WriteLine(newStr); // Output: Hello C#
Trim(): Removes leading and trailing whitespace from the string.
string str = “ Hello World “;
string trimmed = str.Trim();
Console.WriteLine(trimmed); // Output: Hello World
- Verbatim Strings:
In C#, you can define verbatim strings using the @ symbol. This allows the string to preserve whitespace and escape characters, making it easier to work with multi-line strings or regular expressions.
Example:
string path = @”C:\Users\JohnDoe\Documents”;
string multiline = @”This is a
multi-line
string.”;
- Substring
string subGreeting = greeting.Substring(0, 5);
Console.WriteLine(subGreeting); // Output: Hello
If statements is a conditional statement that allows you to execute a block of code only if a specified condition evaluates to true. Allowing the program to take different actions based on the outcome of a condition.
Else statements is a conditional statement that allows you to execute a block of code only if the if statement is false.
Else if statements are another form of a conditional statements that allows you to implement a new specified condition and executes the block of code if the pervious statement is false and this one is true.
if (condition)
{
// Execute if true
}
else if (condition)
{
// Execute if true
}
else
{
// Execute if false
}
A bool (short for Boolean) is a fundamental data type used to represent true/false values. It is one of the most commonly used data types for making logical decisions and controlling the flow of a program through conditional expressions and loops.
bool is_true = True;
bool is_false = False;
A nested if statement is a if statements inside of a if statement
if (condition)
{
if (condition)
{
// Do
}
else
{
// Do
}
}
The switch statement is a control structure used to execute one out of many possible blocks of code, depending on the value of an expression. It’s typically used as a more readable alternative to multiple if-else if chains when you need to check the value of a variable against many different possibilities.
switch (expression)
{
case value1:
// Code to execute if expression == value1
break;
case value2: // Code to execute if expression == value2 break; default: // Code to execute if no case matches the expression break; } expression: The value that is being tested.
case: Each case checks if the value of the expression matches the specified value. If a match is found, the associated block of code is executed.
break: The break statement is used to exit the switch block after executing a case. If you omit break, the code will “fall through” and continue to execute subsequent case blocks.
default: This is an optional block that is executed if no case matches the expression.
When should you use if statements over switch cases and switch cases over if statements?
// Switch over if statements
// - Multiple Distinct Options
// - Improves Readability, easier code to read
// - Enum Types, allows to evaluate each enumeration value explicitly
// If statements over switch cases
// - Complex Conditions, handles complex logical conditions that involve multiple comparisons or boolean expressions
// - Ranged Values, checking if a value falls in a certain range
// - Dynamic Conditions, can handle conditions that may change on runtime whereas switch statements work better with static, predefined options.
Loops are control structures that allow you to execute a block of code repeatedly as long as a certain condition is met.
for loop is typically used when you know in advance how many times you need to execute a block of code.
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
while loop is used when you want to continue executing a block of code as long as a specific condition remains true.
while (condition)
{
// Do
}
do-while loop is similar to the while loop but guarantees that the code inside the loop will be executed at least once before checking the condition.
do
{
// Do
}
while (condition)
foreach loop is used to iterate over a collection (such as an array, list, or other enumerable types) without having to manually manage the loop index. It’s ideal when you want to access each item in a collection one by one.
foreach (type item in collection)
{
// code to execute with each item
}
….
break and continue are used in loops but what for?
break: Immediately exits the loop, regardless of the condition.
continue: Skips the current iteration and moves to the next iteration of the loop.