C++ code Please:
1. Write a function to find the first occurrence of a given letter in a string, return the index. If not found, return -1. (2’)
Input example: str = "Hello World!" find(str, 'e') |
Input example: str = "a random string" find(str, '3') |
Output example: 1 |
Output example: -1 |
#include <iostream>
using namespace std;
int find(string s, char c)
{
// looping through each character
for(int i=0; i<s.length(); i++)
if(s[i] == c) // if it is same
return i; // returning the index
return -1; // otherwise comes here to return -1
}
int main() {
// sample output
cout << find("Hello World!", 'e') << endl;
cout << find("a random string", '3') << endl;
}
/*OUTPUT
1
-1
*/
// Please up vote or comment for doubts. Happy Learning!
Get Answers For Free
Most questions answered within 1 hours.