Ejercicio
Base De Datos De Ciudades
Objectivo
Cree una base de datos para almacenar información sobre las ciudades.
En un primer acercamiento, almacenaremos solo el nombre de cada ciudad y el número de habitantes, y asignaremos espacio para hasta 500 ciudades.
El menú debe incluir las siguientes opciones:
1.- Añadir una nueva ciudad (al final de los datos existentes)
2.- Ver todas las ciudades (nombre y habitantes)
3.- Modificar un registro (renombrar y/o cambiar número de habitantes)
4.- Insertar un nuevo registro (en una posición especificada, moviendo los siguientes a la derecha)
5.- Eliminar un registro (moviendo los siguientes a la izquierda para que no queden espacios vacíos)
6.- Buscar en los registros (mostrar los que contienen un determinado texto en su nombre, ya sea en mayúsculas o minúsculas, mediante búsqueda parcial)
7.- Corregir la mayúscula de los nombres (convertir en mayúscula la primera letra y las siguientes después de un espacio, y hacer el resto en minúsculas).
0.- Salida
Ejemplo Ejercicio C#
Mostrar Código C#
using System; // Import the System namespace for basic functionality
using System.Linq; // Import LINQ to use string manipulation and search functionality
class Program // Define the main class
{
// Define the structure for a city
struct City
{
public string Name; // Name of the city
public int Inhabitants; // Number of inhabitants
}
static void Main() // The entry point of the program
{
City[] cities = new City[500]; // Array to store up to 500 cities
int currentCityCount = 0; // Counter to keep track of the current number of cities
while (true) // Infinite loop to display the menu repeatedly
{
// Display the menu options
Console.WriteLine("1. Add a new city");
Console.WriteLine("2. View all cities");
Console.WriteLine("3. Modify a record");
Console.WriteLine("4. Insert a new record");
Console.WriteLine("5. Delete a record");
Console.WriteLine("6. Search in the records");
Console.WriteLine("7. Correct the capitalization of the names");
Console.WriteLine("0. Exit");
Console.Write("Select an option: ");
string choice = Console.ReadLine(); // Read the user's choice
// Perform actions based on the user's choice
switch (choice)
{
case "1": // Add a new city
if (currentCityCount < 500) // Check if there is space for more cities
{
Console.Write("Enter the city name: ");
string name = Console.ReadLine();
Console.Write("Enter the number of inhabitants: ");
int inhabitants = int.Parse(Console.ReadLine());
cities[currentCityCount] = new City { Name = name, Inhabitants = inhabitants }; // Add the city to the array
currentCityCount++;
Console.WriteLine("City added successfully!");
}
else
{
Console.WriteLine("Database is full!");
}
break;
case "2": // View all cities
Console.WriteLine("Cities:");
for (int i = 0; i < currentCityCount; i++)
{
Console.WriteLine($"{cities[i].Name} - {cities[i].Inhabitants} inhabitants");
}
break;
case "3": // Modify a record
Console.Write("Enter the name of the city to modify: ");
string cityToModify = Console.ReadLine();
bool found = false;
for (int i = 0; i < currentCityCount; i++)
{
if (cities[i].Name.Equals(cityToModify, StringComparison.OrdinalIgnoreCase))
{
found = true;
Console.Write("Enter the new name: ");
cities[i].Name = Console.ReadLine();
Console.Write("Enter the new number of inhabitants: ");
cities[i].Inhabitants = int.Parse(Console.ReadLine());
Console.WriteLine("City updated successfully!");
break;
}
}
if (!found) Console.WriteLine("City not found!");
break;
case "4": // Insert a new record
Console.Write("Enter the position to insert at (1 to {0}): ", currentCityCount + 1);
int position = int.Parse(Console.ReadLine()) - 1;
if (position >= 0 && position <= currentCityCount)
{
Console.Write("Enter the city name: ");
string cityName = Console.ReadLine();
Console.Write("Enter the number of inhabitants: ");
int cityInhabitants = int.Parse(Console.ReadLine());
for (int i = currentCityCount; i > position; i--)
{
cities[i] = cities[i - 1]; // Move cities to the right
}
cities[position] = new City { Name = cityName, Inhabitants = cityInhabitants };
currentCityCount++;
Console.WriteLine("City inserted successfully!");
}
else
{
Console.WriteLine("Invalid position!");
}
break;
case "5": // Delete a record
Console.Write("Enter the name of the city to delete: ");
string cityToDelete = Console.ReadLine();
found = false;
for (int i = 0; i < currentCityCount; i++)
{
if (cities[i].Name.Equals(cityToDelete, StringComparison.OrdinalIgnoreCase))
{
found = true;
for (int j = i; j < currentCityCount - 1; j++)
{
cities[j] = cities[j + 1]; // Shift cities to the left
}
currentCityCount--;
Console.WriteLine("City deleted successfully!");
break;
}
}
if (!found) Console.WriteLine("City not found!");
break;
case "6": // Search in the records
Console.Write("Enter the text to search for: ");
string searchText = Console.ReadLine().ToLower(); // Make the search case-insensitive
Console.WriteLine("Search results:");
bool foundSearch = false;
for (int i = 0; i < currentCityCount; i++)
{
if (cities[i].Name.ToLower().Contains(searchText)) // Partial search
{
Console.WriteLine($"{cities[i].Name} - {cities[i].Inhabitants} inhabitants");
foundSearch = true;
}
}
if (!foundSearch) Console.WriteLine("No cities found matching the search criteria.");
break;
case "7": // Correct the capitalization of the names
for (int i = 0; i < currentCityCount; i++)
{
cities[i].Name = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(cities[i].Name.ToLower());
}
Console.WriteLine("Capitalization corrected for all city names.");
break;
case "0": // Exit the program
Console.WriteLine("Exiting program...");
return;
default:
Console.WriteLine("Invalid option! Please try again.");
break;
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(); // Wait for user input before continuing
}
}
}
Salida
1. Add a new city
2. View all cities
3. Modify a record
4. Insert a new record
5. Delete a record
6. Search in the records
7. Correct the capitalization of the names
0. Exit
Select an option: 1
Enter the city name: New York
Enter the number of inhabitants: 2500000
City added successfully!
Press any key to continue...
Código de Ejemplo Copiado!
Comparte este Ejercicio C# Sharp