Search Using Array.

Hey, i was reading up on find function and i came across this line.

size_t find ( const char* s, size_t pos, size_t n ) const;

Correct me if im wrong, but it basically allows us to search a string based on the information inside an array right?

After searching online , i realize that alot of people use it to check how many times a certain character which they input will be in the array.

for example.

array = ["ttt ttt ttt"]
basically , they will input in the character they want to find ,(in this case 't) , and the prog will count how many times 't' appears in the array.


What i am curious to know if this function can be used like the way i did below. i tried typing out this code but it dosnt seem to work. What i am trying to do is to input in a string and then using the array to find if any of the characters in the array exist.



1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
   string str = "BE";

   int b = 0 ;

   const int arraySize2 = 19;
   char array2[arraySize2] ={'A','B','E','F','G','H','J','K','N','O','P','Q','R','S','T','U','W','Y','Z'};

   for (int i = 0 ; i < str.length() ; i ++)
     int b = str.find(array2[i]);

   cout << b << endl;
std::string::find( char ch, size_t pos = 0 ) returns the index of the first occurrence of ch in the string, or std::string::npos
if ch was not found. If pos is greater than zero, then the function begins searching the string at the specified index
instead of the beginning of the string.

To count the number of occurrences of a character in a string using only methods on std::string, you need to write a
loop.

Using the std::count() algorithm, however, you can do it in one line of code:

1
2
3
std::string str = "ZZABCZZ";
std::cout << "Number of occurrences of 'Z' in str is: "
    << std::count( str.begin(), str.end(), 'Z' ) << std::endl;

but it only allows to search for a single char at a time right? i was thinking if it can be used to find an accorance of any of the characters which i have stored in the array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int str_count(string w , string f)
{
	string cw = w;
	int countx = 0;
	size_t found;
	found = cw.find(f);
	while( int(found) > -1 )
	{
		found = cw.find(f);
		if (int(found) > -1)
		{
			++countx;
			cw.replace(found , f.length(),"");
		}
	}
	return countx;
}
Topic archived. No new replies allowed.