Tuesday, 12 April 2016

C And C++ Program to find the first occurrence of a character in a string Problem Solution.


C Solution:

#include <stdio.h>
#include <string.h>
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main()
{
    char str[1000];
    char toFind;
    int cnt = 0,i = 0;

    printf("Enter any string: ");
    gets(str);
    printf("Enter character to be searched: ");
    scanf("%c",&toFind);
    while(str[i]){
        if(str[i] == toFind)cnt++;
        i++;
    }
    if(cnt == 0) printf("'%c' not found.", toFind);
    else printf("Index of '%c' is %d.", toFind, cnt);

    return 0;
}

C++ Solution:

#include <iostream>
#include <string>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    string str;
    char toFind;
    int cnt = 0,i = 0;

    cout << "Enter any string: ";
    getline(cin,str);

    cout << "Enter character to be searched: ";
    cin >> toFind;
    while(str[i]){
        if(str[i] == toFind)cnt++;
        i++;
    }
    if(cnt == 0) cout << "'" << toFind << "' not found." << endl;
    else cout << "Index of '" << toFind << "' is " << cnt << "." << endl;

    return 0;
}

No comments:

Post a Comment