About Functions

How to define a function with two arguments – string and character that returns the index of second occurrence of that character in the string or -1 if there are less than two occurrences.
Well, write a function that has a string argument 'str' and a char argument 'ch'. Then use either a count variable and a for loop, or string::find (twice) to find the index.
Hello, hope this function will help you solve the problem:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
using namespace std;

short function (char* MyString, char MyChar, short num) {
	short times = 0, i, lastINDEX = 0, lenght = strlen (MyString) + 1; //declare local variables and initilize required
	for (i = 0; i < lenght; i++) {
		if (MyString [i] == MyChar) {
			lastINDEX = i;  //record index of last character seen
			++times;  //record how many times MyChar has benn seen
			continue; // other if statements are irelevant if true, so skip them and speed up :)
		}
		if (times == num) 
			return i;	// return index of MyChar if character is founded so many times as requested
		if (i == lenght - 1) {
			cout << num << ".Character '" << MyChar << "' not found but index of last character found is ";
			return lastINDEX; // num-th character not foud so return last character
		}
	}
	return lastINDEX;  //this return is here only because of compiler warning (it's usleles)
}


int main () {
	char test [] = "here is damn strng to check out the where misterious char s is";

	cout << function (test, 's', 2)  << endl; 
/* 1.arg = enter string where to search
2.arg = enter char which to search 
3.arg = how many times to search for that character */

	system ("pause");
	return 0;
}


sasanet croatia
Last edited on
Thanx Sasanet! Your program runs perfectly but I want more simple program without pointers and short functions. It should be as short as possible. :D
yo Uzumaki,
I'm afraid this function can't be more simple :)

maybe string header has some specific functions which may do the same thing but I don't know any.

chears!
hamsterman already posted how it should be done.
Here's a link for you: http://www.cplusplus.com/reference/string/string/find/
short functions

The return type is short (short int to be precise), not the function.

And sasa, yes actually this can be written a LOT shorter and without pointers.
Last edited on
Topic archived. No new replies allowed.