The Character Finding Algorithm

Written by Raza on. Posted in C++

We saw how to match the two given strings last time and determine whether they first of them is less than, greater than or equal to the second string. We developed a simple string matching algorithm for that purpose. Similarly we also want to perform a number of other operations on our strings and need to find certain patterns and keys in them. Today we shall develop a simple character finding algorithm in a given string. Let us see which things we need to find out.

We need to find out that a given string has our particular character or not? Suppose we have a string `this way!`, and we want to find out the first occurrence of the character `s`. We have to check whether it exists at all in that string or not and if yes, we need to find index of its occurrence as well. In case that character is not present in the given string, we would return -1 as the index in our character finding algorithm.

In order to find that character, we would have to traverse the whole string and check it character by character for our particular character to find. As soon as we encounter the character, we store its index in a variable with us. When we have found the character, we surely do not need to check any more. So we had better stop there.

A simple form of this character finding algorithm would look like this.

 

int find_character (const string &str, const char key)
{
.  int i = 0 ;
.  int index = -1 ;
.  while (str[i] != '\0')
.  {
.   if (str[i] == key)
.   {
.    index = i ;
.    break ;
}
.   ++i ;
.  }
.  return index ;
}
int main ()
{
.  string str = "abc 10" ;
.  char key = 'c' ;
.  cout << find_character(str, key) ;
}

 

Tags: , , ,

Trackback from your site.

Leave a comment