Tuesday, 12 April 2016

C And C++ Program to find length of a string without library function Problem Solution.


C Solution:

#include <stdio.h>
#include <string.h>
 /*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    char *str;
    int cnt = 0;

    str = (char*) malloc (sizeof(char));
    printf("Enter any string: ");
    gets(str);

    while(str[cnt] != '\0')cnt++;

    printf("Length of \"%s\" = %d.", str, cnt);

    return 0;
}

C++ Solution:

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

    string str;
    int cnt = 0;

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

    while(str[cnt] != '\0')cnt++;

    cout << "Length of \"" << str << "\" = " << cnt << endl;

    return 0;
}

No comments:

Post a Comment