✍️ Practice (Strings)
1. Print Each Character
Create a function that prints every character of a string on its own line
👀Hint
The method signature is as follows
static void PrintCharacters(string message)
{
// print smthing
}
💡Solution
static void PrintCharacters(string message)
{
foreach(char c in message)
{
Console.WriteLine(c);
}
}
2. Character Frequency
Create a function that returns the frequency of a given character in a string
👀Hint
The method signature is as follows
static int GetCharacterFrequency(char letter, string message)
{
// return smthing
}
💡Solution
static int GetCharacterFrequency(char letter, string message)
{
int total = 0;
foreach(char c in message)
{
if(c == letter)
{
total++;
}
}
return total;
}
Example usage:
string message = "wow hello there, welcome to my house";
Console.WriteLine(GetCharacterFrequency('w', message));
3. Palindrome
Create a function to determine if a string is a palindrome. A palindrome reads the same forwards and backwards.
👀Hint
Compare the character at the start index with the character at the end index. If a mismatch is found at any point, the string is not a palindrome, and you can stop immediately.
💡Solution
static bool IsPalindrome(string word)
{
int start = 0;
int end = word.Length - 1;
while(start < end)
{
if(word[start] != word[end])
{
return false;
}
start++;
end--;
}
return true;
}
Example usage:
Console.WriteLine(IsPalindrome("racecar")); // True
Console.WriteLine(IsPalindrome("hello")); // False
4. Reverse a String
Create a function to reverse the order of characters in a given string
👀Hint
Use the two-pointer or swap technique.
There are MANY correct solutions btw
💡Solution
You could
static string ReverseString(string word)
{
char[] newWord = new char[word.Length];
int start = 0;
for(int end=newWord.Length - 1; end>=0; end--)
{
newWord[start] = word[end];
start++;
}
return new string(newWord);
}
Example usage:
Console.WriteLine(ReverseString("hello")); // olleh
Console.WriteLine(ReverseString("racecar")); // racecar