+ 4
C++ Length of a string
How do you find the length of a string in c++ without using library functions?
8 Respuestas
+ 4
by using pointers we can do that like this example :-
unsigned int StringLength( const char s[] ) { unsigned int counter = 0;
while ( *s++ )
counter++;
return counter; }
by using pointer to the string and increment the value of string pointer *s++ and counter we can find the length of string
ex:-
int length(const char* str){
int i = 0;
for(; *str++; i++)
{return i; }
+ 5
@Martin but @Ms_Shugg wants without without library functions that's why I take character array unless i also post like you explain
+ 3
@Martin my mistake just miss that thing look at this
#include<iostream>
using namespace std;
int main()
{
char a[30];
int i;
cout<<"Enter a string:";
gets(a);
for(i=0;a[i]!='\0';++i);
cout<<"\nLength of the string '"<<a<<"' is "<<i;
return 0;}
well we can do like this too
+ 2
You get a random string and count the number of characters it has.Like
input: "hello"
output:5
Using a for,while or do...while instead of str.length() or str.size()