Exercise
Function Modify A Letter In A String
Objective
Write a C# function named "ChangeChar" to modify a letter in a certain position (0 based) of a string, replacing it with a different letter:
string sentence = "Tomato";
ChangeChar(ref sentence, 5, "a");
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Function to modify a character in a string at a given position
public static void ChangeChar(ref string str, int position, string newChar)
{
// Convert the string into a character array (since strings are immutable in C#)
char[] charArray = str.ToCharArray();
// Replace the character at the specified position with the new character
charArray[position] = newChar[0]; // newChar is assumed to be a single character string
// Convert the character array back to a string and update the original string
str = new string(charArray);
}
// Main method where the ChangeChar function is called
public static void Main()
{
// Original string
string sentence = "Tomato";
// Call the ChangeChar function to change the character at position 5 to 'a'
ChangeChar(ref sentence, 5, "a");
// Print the modified string
Console.WriteLine("Modified string: " + sentence);
}
}