Exercise
Strings Manipulation
Objective
Write a C# program that asks the user for a string and:
- Replace all lowercase A by uppercase A, except if they are preceded with a space
- Display the initials (first letter and those after a space)
- Display odd letters uppercase and even letter lowercase
The program must display all generated strings.
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace to use its functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
Console.Write("Enter a string: "); // Prompt the user to input a string
string input = Console.ReadLine(); // Read the input from the user
// Call the methods to manipulate and display the string
string replacedString = ReplaceLowercaseA(input);
string initials = GetInitials(input);
string oddEvenString = OddEvenCase(input);
// Display all the manipulated strings
Console.WriteLine($"Replaced String: {replacedString}"); // Display the string with replaced characters
Console.WriteLine($"Initials: {initials}"); // Display the initials
Console.WriteLine($"Odd/Even Case: {oddEvenString}"); // Display the odd/even case transformation
}
// Method to replace all lowercase 'a' by uppercase 'A', except when preceded by a space
static string ReplaceLowercaseA(string text)
{
char[] chars = text.ToCharArray(); // Convert the string to a character array
for (int i = 0; i < chars.Length; i++)
{
// Check if the current character is 'a' and not preceded by a space
if (chars[i] == 'a' && (i == 0 || chars[i - 1] != ' '))
{
chars[i] = 'A'; // Replace 'a' with 'A'
}
}
return new string(chars); // Convert the modified character array back to a string
}
// Method to extract the initials (first letter and those after a space)
static string GetInitials(string text)
{
string initials = string.Empty; // Initialize an empty string for initials
// Loop through each character of the input text
for (int i = 0; i < text.Length; i++)
{
if (i == 0 || text[i - 1] == ' ') // If it's the first character or follows a space
{
initials += text[i]; // Add the character to the initials string
}
}
return initials; // Return the initials string
}
// Method to display odd-index letters in uppercase and even-index letters in lowercase
static string OddEvenCase(string text)
{
char[] chars = text.ToCharArray(); // Convert the string to a character array
for (int i = 0; i < chars.Length; i++)
{
if (i % 2 == 0) // Even index (0, 2, 4, ...)
{
chars[i] = Char.ToLower(chars[i]); // Make even-index letters lowercase
}
else // Odd index (1, 3, 5, ...)
{
chars[i] = Char.ToUpper(chars[i]); // Make odd-index letters uppercase
}
}
return new string(chars); // Convert the modified character array back to a string
}
}