Find the position of a letter using FOR

Asked

Viewed 56 times

1

I’m doing a project that is as follows.

The Program asks the user a text and a letter that will be searched within this text and I want it to return me the position.

Ex.: If you put the word "Table" and I want to look for the letter "s" it returns me the answer of "3" which is the position that is the letter "s"

I’m using this code.

string Texto = "", Palavra = "", resposta = "";
int contador = 0;

Texto = txttexto.Text;
Palavra = txtpalavra.Text;

for (int i = 0; i < Texto.Length; i++)
{
    if (Texto.Contains(Palavra))
    {
        contador++;             
    }
}

txtresposta.Text = Convert.ToString(contador);
  • 1

    But what is your doubt?

  • The Code does not return me the position of the letter, I wanted it to return me the position and it returns me the letter.

1 answer

4


There are some things wrong there, but I’ll just focus on the crucial error of your task.

This block of code

if (Texto.Contains(Palavra))
{
    contador++;             
}

checks whether the variable Texto contains the variable value Palavra (that should be called letra, right?).

Let’s take a test tabletop (sorry, I couldn’t help).

Each row of the table below represents a loop of repetition

i | Texto | Palavra | Texto.Contains(Palavra) | contador | 
- | ----- | ------- | ----------------------- | -------- |
0 | Mesa  | s       | true                    |    0     |
1 | Mesa  | s       | true                    |    1     |
2 | Mesa  | s       | true                    |    2     |
3 | Mesa  | s       | true                    |    3     |

You understand the problem?

The value of contador will always be the index of the last letter of the word.


The first thing you need to keep in mind is that in C#, a string is a string (for simplicity, a array of char). And, like every C#indexed collection, the first item is at position 0. Therefore, from the moment you know the index of a letter, you will need to increment it to 1 to present to the user.

The simplest way to solve this problem is by using the method IndexOf. Something like:

public static void Main()
{
    string texto = "mesa", letra = "s";
    var pos = texto.IndexOf(letra) + 1;
    Console.WriteLine($"Encontrada a letra {letra} na palavra {texto} na posição {pos}");
}

See working on . NET Fiddle

I imagine you’re learning and that’s why you did it using the for, then here a functional code with the same structure as its original code:

public static void Main()
{
    string texto = "mesa"; 
    char letra = 's';

    int i = 0;
    for (i = 0; i < texto.Length; i++)
    {
        if (texto[i] == letra)
            break;            
    }

    Console.WriteLine(Convert.ToString(i + 1));
}

See working on . NET Fiddle

  • It worked! Thank you, it helped me a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.