Ejercicio
Función escribir subrayado
Objetivo
Crear una función capaz de escribir centrado en pantalla el texto que se indica como parámetro (suponiendo un ancho de pantalla de 80 caracteres) y luego subrayarlo (escribiendo varios guiones bajo esa palabra):
WriteUnderlined("¡Hola!");
Código de Ejemplo
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Function to write the given text centered on the screen and then underline it
public static void WriteUnderlined(string text)
{
// Define the screen width as 80 characters
int screenWidth = 80;
// Ensure the text is not longer than the screen width,
// if it is, truncate it to avoid issues with padding calculation
if (text.Length > screenWidth)
{
text = text.Substring(0, screenWidth);
}
// Calculate the padding required on the left side to center the text
int padding = Math.Max(0, (screenWidth - text.Length) / 2);
// Write the text with the calculated padding before it, effectively centering it
Console.WriteLine(new string(' ', padding) + text);
// After the text, print a line of hyphens, matching the length of the text
// The number of hyphens is equal to the length of the text
Console.WriteLine(new string(' ', padding) + new string('-', text.Length));
}
// Main method to call the WriteUnderlined function and display the result
public static void Main()
{
// Call the WriteUnderlined function with the text "Hello!"
// This will print the text centered on a screen of 80 characters width, and underline it
WriteUnderlined("Hello!");
}
}