Mactin
Mactin

Reputation: 17

Understanding String::Find In C++

I've been given a programming task that involves taking away certain letters in a string. I was trying out different ways to do this when I found the public member function string find. To put it short I was testing out the function via this program :

#include <iostream>
#include <string>
using namespace std;

int main()
{

  string Word = "Applejuice";
  
  cout<<Word.find("e")<<endl;






  return 0;


}

So when I put in a letter such as "e" I get the number 4 which confuses me because I thought the function will count all the letters in that specific word such as apple juice. Also, when I use a letter that is not used in that word I get numbers like 18446744073709551615 for example when I put in X for e in the code above.

Could someone explain why this is happening, please?

Upvotes: 0

Views: 6249

Answers (2)

ASLAN
ASLAN

Reputation: 639

string.find() will return the position of the first character of the first match. If no matches were found, the function returns string::npos.

Therefore the number (18446744073709551615) you are getting is the string::npos

If you want to search for an only a single character in the string you can use the following code

#include <iostream> 
#include <string> 
using namespace std; 
  
// Function that return count of the given  
// character in the string 
int count(string s, char c) 
{ 
    // Count variable 
    int res = 0; 
  
    for (int i=0;i<s.length();i++) 
  
        // checking character in string 
        if (s[i] == c) 
            res++; 
  
    return res; 
} 
  
// Driver code 
int main() 
{ 
    string str= "Applejuice"; 
    char c = 'e'; 
    cout << count(str, c) << endl; 
    return 0;
}

If you want to avoid some random large values as output i.e. string::npos you can just add check for it like following:

 if(Word.find("e") != string::npos)
 {
    ...
 }

Upvotes: 2

Farhad Sarvari
Farhad Sarvari

Reputation: 1081

Method find from class string return the position of the first character of the first match. Return type of find is size_t and since size_t is unsigned integral so if no match were found return string::nopos so you should compare the outputof find with string::nopos.

 if(Word.find("e") != string::nopos)
 {
    ...
 }

Upvotes: 0

Related Questions