Finding string length using the strlen() function – CSKC
Sign In

Search

Code Learning #CPP#2556    siteicon   siteicon  

Finding string length using the strlen() function

Finding the length of an initialised character array or the c-style string using the strlen() function.

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

TC++ #2556

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :

Code Understanding

#include <string.h>
This header file is included to ensure that the strlen() function can be used. Some compilers may include this automatically along with iostream.

char str[]=”Programming is magic”; //Here we are simply initialising the string.

cout<<“String length of \””<<str<<“\” is “<<strlen(str)<<” 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. The strlen(str) function has been used here directly within the cout chain. It outputs the integer number containing the string length.

 

Notes

  • On modern compilers the <cstring> is a better choice instead of <string.h> for proper support of unicode and all other modern variations.
  • Although strlen() function is used by inclusion of <string.h> or <cstring>header file, one may observe its proper functionality without including this header. This is a compiler implementation issue and student as advised to include them always.

Common Errors

  • str is just a given variable name here. some students feel that this is the only name allowed to be given. The most common mistake they do is they always write strlen(str) even if variable name given is something else. For. e.g if
    char s1[] is given then strlen(s1) has to be used.


Suggested Filename(s): strlen.cpp



Share

Created: 12-Jan-2018 22:23 | Updated: 15-Nov-2018 02:37|