C++ program to find length of string. Here I have given four methods to find length of string like using strlen() function, without using strlen() function, using recursion, using pointer.
Method 1 : C++ program to find length of a string without using strlen() function
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char str[20];
int i;
cout<<"Enter String : ";
cin>>str;
for(i=0;str[i]!='\0';i++);
cout<<"Length of string is : "<<i;
return 0;
}
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char str[20];
int i;
cout<<"Enter String : ";
cin>>str;
for(i=0;str[i]!='\0';i++);
cout<<"Length of string is : "<<i;
return 0;
}
Method 2 : C++ program to find length of a string using strlen() function
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char temp,str[50];
int lenght;
cout<<"Enter String : ";
cin>>str;
lenght=strlen(str);
cout<<"Length of string is : "<<lenght;
return 0;
}
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char temp,str[50];
int lenght;
cout<<"Enter String : ";
cin>>str;
lenght=strlen(str);
cout<<"Length of string is : "<<lenght;
return 0;
}
Method 3 : C++ program to find length of a string using pointer
#include<iostream>
using namespace std;
int main()
{
char str1[20],*p;
int i;
cout<<"Enter string : ";
cin>>str1;
p=str1;
for(i=0;*p!='\0';i++,p++);
cout<<"Length of string : "<<i;
return 0;
}
using namespace std;
int main()
{
char str1[20],*p;
int i;
cout<<"Enter string : ";
cin>>str1;
p=str1;
for(i=0;*p!='\0';i++,p++);
cout<<"Length of string : "<<i;
return 0;
}
Method 4 : C++ program to find length of a string using recursion
#include<iostream>
using namespace std;
int lenght(char *str,int i)
{
if(str[i]=='\0')
return i;
else
return lenght(str,i+1);
}
int main()
{
char str[50];
cout<<"Enter string : ";
cin>>str;
cout<<"Length of string : "<<lenght(str,0);
return 0;
}
using namespace std;
int lenght(char *str,int i)
{
if(str[i]=='\0')
return i;
else
return lenght(str,i+1);
}
int main()
{
char str[50];
cout<<"Enter string : ";
cin>>str;
cout<<"Length of string : "<<lenght(str,0);
return 0;
}
No comments:
Post a Comment