Sunday 23 February 2014

Searching For A Character in a String - C++ Source Code

Here is another string-manipulation program. The program searches a character in a user given string, and if it finds the character, it displays the position, and if the character is not found the program displays a not-found message.

Code:
//Support us by sharing, commenting, and visiting often! :)
#include<iostream.h>
#include<string>
void main()
{
    int i;
    char a[100],b;
    cout<<"Enter the string\n";
    cin.getline(a, 50);
    cout<<"Enter the letter\n";
    cin>>b;
    int flag=0;
    for(i=0;i<strlen(a);i++)
    {
        if(b==a[i])
        {
              cout<<"Found at "<<i+1<<" :)\n";
              flag++;
        }
    }
    if(flag==0)
    {
        cout<<"Character not found! :(\n";
    }
}

For newer IDEs, visit this page.

Working:

We first input the string from the user and the character to be searched. We also declare an integer 'flag' and initially set it to 0. A for loop is initiated. If the character the user entered is same as the character the for loop is at, we output the position just after the position of the for loop (because, array usually begins at 0).
Also, the integer 'flag' is decremented. Outside the loop, if the flag is still equal to 0, the program outputs the error message, and if it is more than 1, it does nothing. Two sample outputs are given below..



Happy Coding!
:)

No comments:

Post a Comment

You might also like