- Back to Home »
- Tener acceso a los caracteres individuales
Posted by : Unknown
martes, 17 de junio de 2014
Puede utilizar la notación de matrices con un valor de índice para obtener acceso de sólo lectura a caracteres individuales, como en el ejemplo siguiente:
string s5 = "Printing backwards"; for (int i = 0; i < s5.Length; i++) { System.Console.Write(s5[s5.Length - i - 1]); } // Output: "sdrawkcab gnitnirP"
Si los métodos String no proporcionan la funcionalidad necesaria para modificar caracteres individuales en una cadena, puede utilizar un objeto StringBuilderpara modificar los caracteres individuales "en contexto" y crear a continuación una nueva cadena para almacenar los resultados mediante los métodosStringBuilder. En el ejemplo siguiente, suponga que debe modificar la cadena original de una forma determinada y almacenar a continuación los resultados para su uso futuro:
string question = "hOW DOES mICROSOFT wORD DEAL WITH THE cAPS lOCK KEY?"; System.Text.StringBuilder sb = new System.Text.StringBuilder(question); for (int j = 0; j < sb.Length; j++) { if (System.Char.IsLower(sb[j]) == true) sb[j] = System.Char.ToUpper(sb[j]); else if (System.Char.IsUpper(sb[j]) == true) sb[j] = System.Char.ToLower(sb[j]); } // Store the new string. string corrected = sb.ToString(); System.Console.WriteLine(corrected); // Output: How does Microsoft Word deal with the Caps Lock key?