Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi i want to display string in vc++ which has particular word in it.

for example

String 1 Wcout <<"this is tom" <<endl;


String 2 Wcout <<"tom and jerry is a cartoon show" <<endl;

String 3 Wcout <<"i am BS Computer science student" <<endl;

String 4 Wcout <<"Tom cruise is my favorite actor" <<endl;

String 5 Wcout <<"C++ is a object-oriented language" <<endl;



now i want string in my output which has word tom in it..so i want string1, string2 and string4 as my output..should i use find function for it. with which parameter i should use it. or is there any better way to implement such a logic.
Posted

1 solution

A possible solution according to the requirements set could be:

C++
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

#define STRING_ARRAY_LENGTH 5

bool findString(std::string original, std::string search)
{
	/*
		this function tries to find a string inside another string.

		original - string with text to be searched.
		search - string with text to be found.

		returns true if 'search' exists in 'original'

		note: this function is not case sensitive.
	*/

	std::string::size_type foundPosition;

	std::transform(original.begin(), original.end(), original.begin(), ::tolower);
	std::transform(search.begin(), search.end(), search.begin(), ::tolower);

	foundPosition = original.find(search);

	return foundPosition != std::string::npos;
}

int main(void)
{
	std::string* myStringCollection = new std::string[STRING_ARRAY_LENGTH]
	{
		"this is tom",
		"tom and jerry is a cartoon show",
		"i am BS Computer science student",
		"Tom cruise is my favorite actor",
		"C++ is a object-oriented language"
	};

	int myStringIndex = 0;

	std::string mySearchString("tom");

	while(myStringIndex < STRING_ARRAY_LENGTH)
	{
		if ( findString(myStringCollection[myStringIndex], mySearchString) )
			std::cout << myStringCollection[myStringIndex] << std::endl;

		myStringIndex++;
	}

	return 0;
}


NOTE: This example was compiled in gcc.

JAFC
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900