← C# EspañolChapter 09 of 13

Cadenas de Texto

## Objetivos de Aprendizaje - Manipular cadenas de texto - Usar interpolación de cadenas - Trabajar con StringBuilder - Dominar métodos de cadenas ## Fundamentos de Cadenas ### Declaración ```csharp string name = "Alice"; string empty = ""; string nullStr = null; string empty2 = string.Empty; ``` ### Inmutabilidad ```csharp // Las cadenas son inmutables - las operaciones crean nuevas cadenas string s = "Hello"; s = s + " World"; // Crea nueva cadena, s ahora es "Hello World" ``` ## Operaciones con Cadenas ### Concatenación ```csharp string first = "Hello"; string second = "World"; string combined = first + " " + second; // "Hello World" string combined2 = string.Concat(first, " ", second); string combined3 = string.Join(" ", first, second); // "Hello World" ``` ### Métodos de Cadena ```csharp string text = " Hello, World! "; text.Length; // 17 (con espacios) text.Trim(); // "Hello, World!" text.TrimStart(); // "Hello, World! " text.TrimEnd(); // " Hello, World!" text.ToLower(); // " hello, world! " text.ToUpper(); // " HELLO, WORLD! " text.Trim().ToLower(); // Encadenado ``` ### Búsqueda ```csharp string text = "Hello, World!"; text.IndexOf("World"); // 7 text.IndexOf("world"); // -1 (distingue mayúsculas) text.LastIndexOf("o"); // 8 text.Contains("World"); // true text.StartsWith("Hello"); // true text.EndsWith("!"); // true ``` ### Subcadena ```csharp string text = "Hello, World!"; text.Substring(7); // "World!" text.Substring(0, 5); // "Hello" text.Substring(7, 5); // "World" ``` ### Split y Join ```csharp string csv = "Alice,Bob,Charlie"; string[] names = csv.Split(','); // ["Alice", "Bob", "Charlie"] string joined = string.Join(", ", names); // "Alice, Bob, Charlie" // Split con RemoveEmptyEntries string text = "One,,Two,,Three"; string[] parts = text.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); ``` ### Reemplazar ```csharp string text = "Hello, World!"; text.Replace("World", "C#"); // "Hello, C#!" text.Replace("o", "0"); // "Hell0, W0rld!" text.Replace(" ", ""); // "Hello,World!" ``` ### Pad y Trim ```csharp string num = "42"; num.PadLeft(5, '0'); // "00042" num.PadRight(5, '0'); // "42000" // Trim de caracteres específicos string text = "###Hello###"; text.Trim('#'); // "Hello" text.TrimStart('#'); // "Hello###" text.TrimEnd('#'); // "###Hello" ``` ## Interpolación de Cadenas (C# 6+) ### Sintaxis Básica ```csharp string name = "Alice"; int age = 30; string message = $"Nombre: {name}, Edad: {age}"; // "Nombre: Alice, Edad: 30" ``` ### Expresiones ```csharp int a = 5, b = 3; Console.WriteLine($"{a} + {b} = {a + b}"); // "5 + 3 = 8" Console.WriteLine($"{a} * {b} = {a * b}"); // "5 * 3 = 15" Console.WriteLine($"{{literal}}"); // "{literal}" ``` ### Formato ```csharp decimal price = 19.99m; DateTime today = DateTime.Now; Console.WriteLine($"Precio: {price:C}"); // "Precio: $19.99" Console.WriteLine($"Fecha: {today:yyyy-MM-dd}"); // "Fecha: 2024-01-15" Console.WriteLine($"Pi: {Math.PI:F2}"); // "Pi: 3.14" Console.WriteLine($"{42:D5}"); // "00042" ``` ### Cadena Literal Raw (C# 11+) ```csharp string json = """ { "name": "Alice", "age": 30 } """; string path = $""" C:\Users\{Environment.UserName}\Documents """; ``` ## StringBuilder ### Cuándo Usarlo ```csharp // Malo para muchas concatenaciones string result = ""; for (int i = 0; i < 1000; i++) { result += i.ToString(); // ¡Crea 1000 cadenas! } // Bueno - cadena mutable StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.Append(i); } string result = sb.ToString(); ``` ### Métodos de StringBuilder ```csharp StringBuilder sb = new StringBuilder(); sb.Append("Hello"); // "Hello" sb.AppendLine(); // "Hello\n" sb.AppendLine("World"); // "Hello\nWorld\n" sb.AppendFormat("{0:C}", 19.99m); // Agregar formateado sb.Length; // Longitud actual sb.Clear(); // Limpiar todo sb.Remove(0, 5); // Remover caracteres sb.Insert(0, "Start "); // Insertar en posición sb.Replace("World", "C#"); // Reemplazar texto ``` ### Inicialización de StringBuilder ```csharp StringBuilder sb = new StringBuilder(); StringBuilder sb2 = new StringBuilder(100); // Capacidad inicial StringBuilder sb3 = new StringBuilder("Hello", 100); ``` ## Comparación de Cadenas ### Opciones ```csharp string a = "Hello"; string b = "hello"; // Comparación sensible a mayúsculas bool equal = a == b; // false bool equalIgnoreCase = a.Equals(b, StringComparison.OrdinalIgnoreCase); // true // String.Compare int result = string.Compare(a, b); // 1 (a > b) int result2 = string.Compare(a, b, StringComparison.OrdinalIgnoreCase); // 0 // CompareTo int result3 = a.CompareTo(b); // 1 ``` ### Enum StringComparison | Valor | Descripción | |-------|-------------| | Ordinal | Binario, sensible a mayúsculas | | OrdinalIgnoreCase | Binario, insensible a mayúsculas | | CurrentCulture | Usa información cultural, sensible a mayúsculas | | CurrentCultureIgnoreCase | Usa información cultural, insensible a mayúsculas | ## Manejo de Cadenas Null ### Operaciones Seguras ```csharp string? nullStr = null; // Métodos seguros que no lanzan excepción nullStr?.Length; // null nullStr ?? "default"; // "default" nullStr?.ToUpper(); // null // Verificar null if (!string.IsNullOrEmpty(nullStr)) { Console.WriteLine(nullStr); } if (!string.IsNullOrWhiteSpace(nullStr)) { Console.WriteLine(nullStr); } ``` ### string.IsNullOrEmpty vs string.IsNullOrWhiteSpace ```csharp string.Empty; // IsNullOrEmpty: true, IsNullOrWhiteSpace: true null; // IsNullOrEmpty: true, IsNullOrWhiteSpace: true " "; // IsNullOrEmpty: false, IsNullOrWhiteSpace: true "hello"; // IsNullOrEmpty: false, IsNullOrWhiteSpace: false ``` ## Operaciones con Caracteres ### Trabajar con Caracteres ```csharp string text = "Hello"; foreach (char c in text) { Console.WriteLine(c); } char first = text[0]; // 'H' char.IsDigit(first); // false char.IsLetter(first); // true char.IsUpper(first); // true char.ToLower(first); // 'h' ``` ## String Pooling ### Interning ```csharp // El compilador hace interning de literales de cadena string a = "Hello"; string b = "Hello"; Console.WriteLine(a == b); // true (misma referencia) Console.WriteLine(ReferenceEquals(a, b)); // true // Pero no para cadenas en tiempo de ejecución string c = new string("Hello".ToCharArray()); Console.WriteLine(a == c); // true (valor igual) Console.WriteLine(ReferenceEquals(a, c)); // false ``` ## Resumen - Las cadenas son inmutables - las operaciones crean nuevas cadenas - Métodos de cadena: IndexOf, Contains, Split, Replace, Substring - Interpolación de cadenas: $"Hola, {name}" - Usar StringBuilder para muchas concatenaciones - Manejo de null: operadores `??` y `?.` - string.IsNullOrEmpty/IsNullOrWhiteSpace para verificaciones - Insensible a mayúsculas: usar StringComparison

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →