find a given letter within a word

Hi I am a beginner,

Here's the problem I Resolve:
Writing a program capable of finding a given letter within a word entered by the user. The program must identify the positions of sucessives caratère and display the character or characters found in uppercase.

example

Enter a word: extraordinary

Letter seeking: a

Result: extrAordinAry

the letter appears at positions 5 and 11.


difficulty:


Is it possible to use a loop to find the characters in the case where the letter appears more than twice?

I also find it difficult to use toupper and replace to achieve this:

Result: extrAordinAry

Thank you for your help

Here is my C + + code at this time:

#include <iostream>
#include <string>
using namespace std;

int main()
{

string word;
string letter;
int pos1, pos2;


cout << "Enter word more then ten character:\n";
cin>>word;
cout << "Letter to search: ";
cin>>letter;
string str = word;

pos1 = str.find(letter);
pos2 = str.rfind(letter);


cout << "The letter "<<letter<<" find at position "<<pos1+1<<" et "<<pos2+1<<endl;

return 0;
}


I'd try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
// run through the entire string char by char once

for( int i = 0 ; i < str.length() ; i++ ){

	if (str[i] == letter[0]) {  // case sensitive compare
	
		cout << "find at: " << i << endl;
		
		str[i] &= 0xDF;  // kill lower case bit
		
	}

}


This seems cheap, but find() and rfind() do the exact same thing :)
Last edited on
I would first ask, "why are you assuming there will only be 2 repeating letters?".

You have 2 variables declared named pos1 and pos2. What happens if there
is a pos3 or pos4?

Also, when you input the letter, why take in a string? If it's just a letter, why not take in a char?

Off the top of my head, a brute force method would be similar to plexus'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
	
vector<int> pos;

for(int i = 0; i < str.length(); i++)
{
	 if (str[i] == letter) 
	 {
	       str[i] = toupper(str[i]);
	       pos.push_back(i+1);
          }     
}

for (int i = 0; i < pos.size(); i++)
      cout << "find at: " << pos[i] << endl;    
 	


It's almost complete. The number of matches is the size of your vector. The string is already formatted for you.
Last edited on
@IceThatJaw

There is no any need to declare variable match to keep the number of matches.

pos.size() will give you the valid number of matches. Also it will be better to rewrite the code using the for statement based on range.
Last edited on
Topic archived. No new replies allowed.