Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to know the specific letter at the beggining of an input box that is repeated 10 times.

I used a for loop first to repeat the inputbox which contains a word. Then I used an if statement outside and inside the forloop but I dont know how to make the C# 2019 program to count a specific character like "t".

What I have tried:

I have tried a for loop and an if statement, but I don't understand how to make it work.
Posted
Updated 30-May-22 21:15pm
Comments
PIEBALDconsult 30-May-22 21:17pm    
Show us the loop.

The Text property of a TextBox returns a string containing the input so far - and a string can be treated as an array of characters:
C#
string greeting = "Hello World";
Console.WriteLine($"{greeting[0]} {greeting[6]}");
Will print the first letter of each word:
H W

So to find out how many times a character is repeated at the beginning of a string is simple:

1) Create a variable to hold the "compare character" - call it firstChar
2) Set firstChar to the first character in the string
3) Create a variable to hold the identical values count called count, set it to zero.
4) Use a foreach loop to look at each character in the string.
4.1) If the character is not the same as firstChar, exit the loop using break
4.2) Otherwise, increment count
5) After the loop, count will contain the number of identical characters at the beginning of the string.
 
Share this answer
 

The trick here is to construct a test string consisting of the first character in the text repeated 10 times.

C#
string text = "tttttttttt for two";
string  testString = new string(Enumerable.Repeat(text[0], 10).ToArray());

Then simply use the Substring method followed by the Contains method to check for a match.
C#
bool isVerified = text.Substring(0, 10).Contains(testString);

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900