Finding string length using the null finding technique
Finding the length of an initialised character array or the c-style string using the null termination check.
Learning Objectives
- Understanding the use of null character as a method to find the string length.
- Use of cout while printing a string.
- Use of escape sequence for printing special characters.
Source Code
|
|
Alternate (?) : |
Run Output
Code Understanding
char str[]=”Programming is magic”; //Here we are simply initialising the string.
int len=0; //This variable will contain the length as computed in the loop
for(int i=0;str[i]!=’\0′;i++) len++;
This loop increments the count of len until the null (\0) character is found. Finding the null character means that end of string has arrived.
cout<<“String length of \””<<str<<“\” is “<<len<<” characters.”<<endl;
Here we print the output. It contains the original string by just referring its name as str and not as str[]. Please note that escape sequence \“ has been used to print the double quote character itself.
Notes
- Instead of null check programmers frequently use the strlen() function of library from string.h.
Common Errors
- For correct results len should be initialised to 0.
- Students often commit mistake in writing the != (not equal to operator and the null character \0) . Learn it correctly.
Suggested Filename(s): str-len-null.cpp, slennull.cpp
Created: 12-Jan-2018 21:59 | Updated: 15-Nov-2018 02:39|
