Using a while loop to check if a char exists in a string


How can I use a while loop to check if a specific char exists in a string?
for example if my string was "Hello World", and I wanted to check if the char o was in the string, how would I do that with a while loop? I've looked everywhere and haven't had any luck on how to do this.
I guess the first step in the exercise is write a loop that prints each character.

Or if life's too short and you just want the problem solved.
https://www.cplusplus.com/reference/string/string/find/
https://www.cplusplus.com/reference/cstring/strchr/
Hello printfsalad,

1
2
3
4
5
6
7
8
9
size_t index{};

while (index < name.size())
{
        //  Check element of string against desired letter.
	//  Do something is they match.

	index++;
}

"name" came from a different program I used to test this. Since you did not provide any code I do not know what you used.

"size_t" is an alias for "unsigned int" and the ".size()" function, along with some other classes, returns a "size_t" type.

The idea of the while loop is that you step through a string comparing each element against the letter that you want.

As a test define a string and initialize it to "The quick brown fox jumped over the lazy dog" This contains every letter of the alphabet then you could set up the input to enter the letter that you want to find. And comment out the part for entering the string for now.

lastchance wrote:

I guess the first step in the exercise is write a loop that prints each character.


If you can do that it would be easy to modify it to do what you want.

Andy

Edit: typo
Last edited on
Topic archived. No new replies allowed.