Does String Contain


	if (s1.find(s2) != std::string::npos)
		cout << "String found!" << endl;

Do Strings Match


	if (my_string1.compare(my_string2) == 0)		//0=strings are the same
	{
		//Strings match
	}

Does String Start With


	if (CommandResult.find("abc") == 0)

Find first occurrence


	string s1 = "hello world";
	
	if (s1.find(' ') != string::npos)
	{
		cout  << "Space found " << endl;
	}
	else
	{
		cout  << "No spaces found" << endl;
	}

If you want to know where it was found:


	string s1 = "hello world";
	size_t find_result;
		
	if ((find_result = s1.find(' ')) != string::npos)
	{
		cout  << "Space found at character " << find_result << endl;
	}
	else
	{
		cout  << "No spaces found" << endl;
	}

Find last occurance


	string s1 = "hello 12";
	size_t find_result;
		
	if ((find_result = s1.rfind(' ')) != string::npos)	//Searches from the end but still returns an index from the start of the string
	{
		cout  << "Space found at character " << find_result << endl;
	}
	else
	{
		cout  << "No spaces found" << endl;
	}

 

 

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *