Reputation: 25
i'm trying to build a program that can find the order of a certain character in a string this is the code i made :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word="banana";
cout << "a = ";
const char *pad = "";
for (size_t i = 0; i < word.size(); i++)
{
if (word[i] == 'a')
{
cout << pad << (i + 1);
pad = ", ";
}
}
cout << "\n";
return 0; }
and it's working perfectly , the only matter is i want it to print out the last order only .. for more clarity : instead of printing out( a=2 , 4 , 6 ) in the last example i want it to print out (a=6)
Anyone can help?
Upvotes: 1
Views: 573
Reputation: 14064
It's already implemented as the find_last_of
and the rfind
methods of std::string
.
I recommend using one of these methods, but if you still want to implement yourself, you have to reverse the order to start from the end and not the begining, and I think you are looking for the break
statement which stops the loop:
for (size_t i = word.size() - 1; i >= 0; --i)
{
if (word[i] == 'a')
{
cout << pad << (i + 1);
break;
}
}
Break works like this:
Upvotes: 4
Reputation: 7603
Reverse the loop
for (size_t i = word.size()-1; i >= 0; i--) {
...
If not for learning about loops, using the standard functions proposed in other answers are the right way to go.
Upvotes: 3
Reputation: 2892
The simplest way I can think of is to use the stl string find_Last_of function. Below is a small example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word="banana";
int pos = word.find_last_of("a");
cout << "Last occurrence of the letter a is at position " << pos+1 << " array position " << pos <<endl ;
return 0; }
Upvotes: 2
Reputation: 94329
You can use std::string::rfind
to get the index of the last occurrence of some character:
#include <string>
#include <iostream>
int main()
{
std::string s = "banana";
std::string::size_type pos = s.rfind( 'a' );
if ( pos == std::string::npos ) {
std::cout << "letter not found\n";
} else {
std::cout << "letter found at position " << pos + 1 << "\n";
}
}
Upvotes: 2