elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [Ayuda] Contar letras de una cadena C#
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Ayuda] Contar letras de una cadena C#  (Leído 5,094 veces)
Leo_Programador

Desconectado Desconectado

Mensajes: 1


Ver Perfil
[Ayuda] Contar letras de una cadena C#
« en: 30 Noviembre 2014, 07:48 am »


[MOD]: Los códigos deben ir en su respectiva etiqueta.



Hola a todos, basicamente el programa que estoy haciendo es un AHORCADO, mi problema es el siguiente:
En un textbox yo escribo la letra que deseo ingresar para verificar si esta o no en la palabra, el tema es que si la palabra es por ejemplo HIPOPOTAMO, esta tiene 3 "O", y yo obviamente al colocar "O" me escribe solo la primera que encuentra.


la porcion de codigo con mi problema esta aca:

Código
  1. private void button3_Click(object sender, EventArgs e)
  2.        {
  3.            letraIngresada = textBoxLetra.Text;
  4.  
  5.            TextBox[] palabraFinal = { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10, textBox11 };
  6.  
  7.            if (palabraElegida.IndexOf(letraIngresada)>=0)
  8.            {
  9.  
  10.                int x = 0;
  11.                x = palabraElegida.IndexOf(letraIngresada);
  12.  
  13.                palabraFinal[x].Text = textBoxLetra.Text;
  14.  
  15.                for (int i = 0; i < palabraFinal.Length; i++)
  16. {
  17. if (palabraFinal[i].Text=="")
  18.                {
  19.                    x++;
  20.                    x=palabraElegida.IndexOf(letraIngresada,x);
  21.  
  22.                    palabraFinal[x].Text = textBoxLetra.Text;
  23.  
  24.                }
  25.  
  26. }
  27.  
  28.            }
  29.            else
  30.            {
  31.                cont++;
  32.                CambiarImagen(cont);
  33.            }
  34.  
  35.        }
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43. public partial class Form1 : Form
  44.    {
  45.  
  46.        string[] animales = { "rinoceronte", "hipopotamo", "tortuga", "flamenco", "avestruz" };
  47.        string[] FruVer = { "zanahoria", "calabacin", "puerro", "remolacha", "aceituna" };
  48.        string[] objetos = { "ventilador", "heladera", "modular", "mochila", "camperon" };
  49.        string[] paises = { "angola", "australia", "nicaragua", "tanzania", "singapur" };
  50.        int bus;
  51.        string palabraElegida;
  52.        string letraIngresada;
  53.        int cont = 0;
  54.  
  55.  
  56.        public Form1()
  57.        {
  58.            InitializeComponent();
  59.        }
  60.  
  61.        public void Buscar_palabra(string[] vec)
  62.        {
  63.            Random buscar = new Random();
  64.  
  65.            bus = buscar.Next(5);
  66.            palabraElegida = vec[bus];
  67.  
  68.            label_Letra.Text= vec[bus];
  69.        }
  70.  
  71.        private void button3_Click(object sender, EventArgs e)
  72.        {
  73.            letraIngresada = textBoxLetra.Text;
  74.  
  75.            TextBox[] palabraFinal = { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10, textBox11 };
  76.  
  77.            if (palabraElegida.IndexOf(letraIngresada)>=0)
  78.            {
  79.  
  80.                int x = 0;
  81.                x = palabraElegida.IndexOf(letraIngresada);
  82.  
  83.                palabraFinal[x].Text = textBoxLetra.Text;
  84.  
  85.                for (int i = 0; i < palabraFinal.Length; i++)
  86. {
  87. if (palabraFinal[i].Text=="")
  88.                {
  89.                    x++;
  90.                    x=palabraElegida.IndexOf(letraIngresada,x);
  91.  
  92.                    palabraFinal[x].Text = textBoxLetra.Text;
  93.  
  94.                }
  95.  
  96. }
  97.  
  98.            }
  99.  
  100.            //if (palabraElegida.IndexOf(letraIngresada) != -1)
  101.            //{
  102.  
  103.            //    for (int i = 0; i < palabraElegida.Length; i++)
  104.            //    {
  105.            //        palabraFinal[palabraElegida.IndexOf(letraIngresada)].Text = textBoxLetra.Text;
  106.  
  107.            //        palabraFinal[palabraElegida.IndexOf(letraIngresada, palabraElegida.IndexOf(letraIngresada) + 1)].Text = textBoxLetra.Text;
  108.            //    }
  109.  
  110.            //}
  111.            else
  112.            {
  113.                cont++;
  114.                CambiarImagen(cont);
  115.            }
  116.  
  117.        }
  118.  
  119.        private void pictureBox1_Click(object sender, EventArgs e)
  120.        {
  121.            fotoPrincipal.Image = fotoSoga.Image;
  122.            label_Letra.Visible = true;
  123.            textBoxLetra.Visible = true;
  124.            button3.Visible = true;
  125.            pictureBox1.Visible = false;
  126.            groupBox1.Visible = false;
  127.            groupBox2.Visible = true;
  128.  
  129.  
  130.            if (radioButton1.Checked == true)
  131.            {
  132.                Buscar_palabra(animales);
  133.            }
  134.            else if (radioButton2.Checked == true)
  135.            {
  136.               Buscar_palabra(FruVer);
  137.            }
  138.            else if (radioButton3.Checked == true)
  139.            {
  140.              Buscar_palabra(objetos);
  141.            }
  142.            else if (radioButton4.Checked == true)
  143.            {
  144.               Buscar_palabra(paises);
  145.            }
  146.            else MessageBox.Show("Elige una opción por favor.");
  147.  
  148.            if (palabraElegida.Length == 10)
  149.            {
  150.                textBox11.Visible = false;
  151.            }
  152.            if (palabraElegida.Length == 9)
  153.            {
  154.                textBox11.Visible = false;
  155.                textBox10.Visible = false;
  156.            }
  157.            if (palabraElegida.Length == 8)
  158.            {
  159.                textBox11.Visible = false;
  160.                textBox10.Visible = false;
  161.                textBox9.Visible = false;
  162.            }
  163.            if (palabraElegida.Length == 7)
  164.            {
  165.                textBox11.Visible = false;
  166.                textBox10.Visible = false;
  167.                textBox9.Visible = false;
  168.                textBox8.Visible = false;
  169.            }
  170.            if (palabraElegida.Length == 6)
  171.            {
  172.                textBox11.Visible = false;
  173.                textBox10.Visible = false;
  174.                textBox9.Visible = false;
  175.                textBox8.Visible = false;
  176.                textBox7.Visible = false;
  177.            }
  178.  
  179.  
  180.        }
  181.                 public void CambiarImagen(int cont)
  182.          {
  183.              switch (cont)
  184.              {
  185.  
  186.                  case 1: fotoPrincipal.Image = fotoCabeza.Image;
  187.                      break;
  188.                  case 2: fotoPrincipal.Image = fotoBrazo.Image;
  189.                      break;
  190.                  case 3: fotoPrincipal.Image = fotoBrazos2.Image;
  191.                      break;
  192.                  case 4: fotoPrincipal.Image = fotoPanza.Image;
  193.                      break;
  194.                  case 5: fotoPrincipal.Image = fotoPierna.Image;
  195.                      break;
  196.                  case 6: fotoPrincipal.Image = fotoCuerpoEntero.Image;
  197.                      break;
  198.  
  199.                  default:
  200.                      break;
  201.              }
  202.  
  203.              if (cont==6)
  204.              {                
  205.                  Form2 frm = new Form2();
  206.                  frm.Show();
  207.                  again.Visible = true;
  208.                  again.BringToFront();
  209.  
  210.  
  211.              }
  212.  
  213.  
  214.        }
  215.  
  216.  
  217.  
  218.        private void again_Click(object sender, EventArgs e)
  219.        {
  220.            Application.Restart();
  221.  
  222.        }
  223.  
  224.  
  225.    }
  226. }
  227.  


« Última modificación: 30 Noviembre 2014, 09:22 am por Eleкtro » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.777



Ver Perfil
Re: [Ayuda] Contar letras de una cadena C#
« Respuesta #1 en: 30 Noviembre 2014, 09:26 am »

Este snippet de mi vieja biblioteca te debería servir para tus propósitos, la función busca un caracter todas las ocurrencias de un caracter y devuelve todos sus índices.

De todas formas el problema que tienes no tiene mucho misterio, también puedes leer caracter por caracter usando un For, o una pila (usando la Class Stack) podría ser mejor según tus necesidades.

VB.Net:
Código
  1.    ' Find Characters
  2.    ' ( By Elektro )
  3.    '
  4.    ' Usage Examples:
  5.    ' Dim CharIndex As Integer() = FindCharacters("Elektro", "E", IgnoreCase:=True) ' Result: {0, 2}
  6.    '
  7.    ''' <summary>
  8.    ''' Matches a character/string pattern in a String and returns the starting indexes of all concurrences.
  9.    ''' </summary>
  10.    ''' <param name="String">Indicates the string.</param>
  11.    ''' <param name="Characters">Indicates the character(s) to find.</param>
  12.    ''' <param name="IgnoreCase">if set to <c>true</c>, sensitive case is ignored.</param>
  13.    ''' <returns>System.Int32().</returns>
  14.    Public Function FindCharacters(ByVal [String] As String,
  15.                                   ByVal Characters As String,
  16.                                   Optional ByVal IgnoreCase As Boolean = False) As Integer()
  17.  
  18.        Return Enumerable.Range(0, [String].Length).
  19.                          Where(Function(i As Integer) Characters.Select(Function(b1, b2) New With {b2, b1}).
  20.                          All(Function(p) If(IgnoreCase,
  21.                                             [String].ToLower.ToCharArray()(i + p.b2).Equals(Char.ToLower(p.b1)),
  22.                                             [String].ToCharArray()(i + p.b2).Equals(p.b1)))).
  23.                          ToArray()
  24.  
  25.    End Function

C#, traducción al vuelo:
Código
  1. // Matches a character/string pattern in a String and returns the starting indexes of all concurrences.
  2. // ( By Elektro )
  3. //
  4. // Usage Examples:
  5. // Dim CharIndex As Integer() = FindCharacters("Elektro", "E", IgnoreCase:=True) ' Result: {0, 2}
  6. //
  7. /// <summary>
  8. /// Finds the characters.
  9. /// </summary>
  10. /// <param name="String">Indicates the string.</param>
  11. /// <param name="Characters">Indicates the character(s) to find.</param>
  12. /// <param name="IgnoreCase">if set to <c>true</c>, sensitive case is ignored.</param>
  13. /// <returns>System.Int32().</returns>
  14. public int[] FindCharacters(string String, string Characters, bool IgnoreCase = false)
  15. {
  16.  
  17. return Enumerable.Range(0, String.Length).Where((int i) => Characters.Select((b1, b2) => new {
  18. b2,
  19. b1
  20. }).All(p => IgnoreCase ? String.ToLower.ToCharArray()(i + p.b2).Equals(char.ToLower(p.b1)) : String.ToCharArray()(i + p.b2).Equals(p.b1))).ToArray();
  21.  
  22. }
  23.  
  24. //=======================================================
  25. //Service provided by Telerik (www.telerik.com)
  26. //=======================================================

Saludos


« Última modificación: 30 Noviembre 2014, 12:28 pm por Eleкtro » En línea


Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Contar letras minusculas y mayusculas
Ejercicios
kay19 0 11,771 Último mensaje 9 Septiembre 2009, 20:06 pm
por kay19
[C] Contar subcadena en una cadena
Programación C/C++
_*p 0 4,078 Último mensaje 18 Febrero 2011, 19:18 pm
por _*p
contar letras de un texto « 1 2 3 4 »
Programación C/C++
ALONSOQ 33 25,601 Último mensaje 4 Julio 2012, 23:05 pm
por ALONSOQ
contar numero de letras en una palabra de un arreglo.
Programación C/C++
scc2810 1 2,040 Último mensaje 6 Marzo 2017, 00:18 am
por integeroverflow
Contar letras en cualquier oración
Programación C/C++
erickcasita 8 3,521 Último mensaje 7 Enero 2018, 18:10 pm
por vangodp
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines