C++ Length of a string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

C++ Length of a string

How do you find the length of a string in c++ without using library functions?

30th Dec 2017, 5:10 PM
MsShugg😘
MsShugg😘 - avatar
4 Answers
+ 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; }
30th Dec 2017, 5:23 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 5
@Martin but @Ms_Shugg wants without without library functions that's why I take character array unless i also post like you explain
31st Dec 2017, 11:38 AM
GAWEN STEASY
GAWEN STEASY - avatar
+ 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
30th Dec 2017, 6:04 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 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()
30th Dec 2017, 6:55 PM
MsShugg😘
MsShugg😘 - avatar