How to find the last occurrence of character in string with C++

3 Answers

0 votes
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s = "c++ c c# java python";

	size_t pos = s.find_last_of("c");

	cout << pos << endl;

	cout << s.substr(0, pos) << endl;
	cout << s.substr(pos + 1) << endl;

	return 0;
}

/*
run:

6
c++ c
# java python

*/

 



answered Feb 25, 2017 by avibootz
0 votes
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string s = "c++ c c# java python";

	size_t pos = s.find_last_of(' ');

	cout << pos << endl;

	cout << s.substr(0, pos) << endl;
	cout << s.substr(pos + 1) << endl;

	return 0;
}

/*
run:

13
c++ c c# java
python

*/

 



answered Feb 25, 2017 by avibootz
0 votes
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

int main()
{
	string s = "c c++ java php";
	
	int index = s.rfind("p");

	if (index != string::npos) 
		cout << "found at index: " << index << endl;
	else
		cout << "not found" << endl;

	return 0;
}


/*
run:

found at index: 13

*/

 



answered May 29, 2018 by avibootz

Related questions

1 answer 138 views
1 answer 123 views
2 answers 180 views
2 answers 212 views
1 answer 147 views
...