AppDividend
Latest Code Tutorials

C++ strlen() Function Example | strlen() in C++

0

C++ strlen() is an inbuilt function that is used to calculate the length of the string. It is a beneficial method to find the length of the string. The strlen() function is defined under the string.h header file.

C++ strlen()

The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character. If there is no null character in the string, the behavior of the function is undefined.

Syntax

int strlen(const char *str_var);

Here str_var is the string variable of whose we have to find the length.

Parameter

It takes one parameter which is a pointer that points to the null-terminated byte string. The string is terminated by a null character. If a null character does not terminate it, then the behavior is undefined.

Return Value

It returns an integer giving the length of the passed string.

Example programs on strlen() function

Example 1: Write a program to show the mechanism of the strlen() function.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char k[] = "hello world";
  char m[] = "I am the best\n";
  char n[] = "a";
  char o[] = "123";
  int f, i, g, h;
  f = strlen(k);
  i = strlen(m);
  g = strlen(n);
  h = strlen(o);
  cout << "String: " << k << endl;
  cout << "Length: " << strlen(k) << endl;
  cout << "String: " << m << endl;
  cout << "Length: " << strlen(m) << endl;
  cout << "String: " << n << endl;
  cout << "Length: " << strlen(n) << endl;
  cout << "String: " << o << endl;
  cout << "Length: " << strlen(o) << endl;
}

Output

String: hello world
Length: 11
String: I am the best
 
Length: 14
String: a
Length: 1
String: 123
Length: 3

Example 2: Take two input strings and check if the length of both the strings is equal or not using the strlen() function.

See the following code.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char a[] = "Hello I am a geek!";
  char b[] = "I love AppDividend!";
  if (strlen(a) == strlen(b))
  {
    cout << "Length of both the strings are equal";
  }
  else
  {
    cout << "Length of the both the strings are not equal";
  }
}

Output

Length of both the strings are not equal

See also

C++ strstr()

C++ strtok()

C++ strspn()

C++ strpbrk()

C++ strcspn()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.