String search

0 Thamsa Chembe · April 7, 2015
How do you search a string so that if the string begins with the letter "b"  then I can know whether a student will be undergrad or postgrad? So basically I need to know if the string begins with "b" or not.

Post a Reply

Replies

Oldest  Newest  Rating
+1 Franz Schmidt · April 7, 2015
there are multiple ways to do this:

1. use string.find(substring)
string.find(substring) returns the position of where the first substring is found (http://www.cplusplus.com/reference/string/string/find/)
e.g.:
int main(){
  string test;
  cin >> test;
  size_t found = test.find("b");

  if(found == 0){
     cout << "your string starts with b";
  }
}

2. use string.c_str()
string.c_str() converts your string into a char array which means you can check for each character (http://www.cplusplus.com/reference/string/string/c_str/)
e.g.:
int main(){
  string test;
  cin >> test;
  if(test.c_str()[0] == 'b'){
     cout << "your string starts with b";
  }
}

3. use string.at(position)
string.at(position) returns the value of the character at the certain position (http://www.cplusplus.com/reference/string/string/at/)
e.g.:
int main(){
  string test;
  cin >> test;
  if(test.at(0) == 'b'){
     cout << "your string starts with b";
  }
}
  • 1

C++

106,949 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator