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
But what is your doubt?
– Albertt Santos
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.
– Marcos Eduardo