x

C++ Strings

PREV     NEXT

What are Strings?

  • The string is an object of the string class and it is defined in the header file i.e. <string.h>.The string class has many constructors that are called to create a string object.
  • It represents the sequence of characters. The operations which can be performed on strings are comparison, concatenation, conversion, etc.
  • The one dimensional or single dimensional array of characters is known as Strings and is terminated by null character ‘\0’.

For example,

‘Hello’ is a string of 5 characters.


How to define strings in C++?

As in C programming, the collection of characters is stored in the form of arrays and they are supported by C++ programming too. They are known as C-strings. The C-strings arrays are of char type and is terminated by null (\0) character. So, let us see how strings are defined in C++.

For example:

                     char str_arr[ ] = “Hello”;

In the above code you can see that, str_arr is a string and it contains 6 characters. In the C++ programming language, the array holds the null character value which is added to the end of the string automatically.

Let us have a look at the example:

Functions in Strings

C++has a wide range of functions that manipulate the strings. Let us have a look on them:


strcat:

  •  It is a string concatenate function. It will concatenate or join the second string with the first string at the end.

Let us have a look at the example:

strcpy:

  • It is a string copy function. It will copy the first string into second string.

Let us have a look at the example:

strcmp:

  • It is a string compare function. In this function it compares the two strings if the strings are equal it will return 0 or else if the strings are not equal it will return 1.

Let us have a look at the example:

strlen:

  •  It is a string length function. It will return the length of a string.

Let us have a look at the example:

strchr:

  • In this it will take the two arguments string and character. It will searches for the character from the given string.

Let us have a look at the example:

strstr:

  •  It will take two arguments string and destination. It will search the first occurrence of string in the first string.

Let us have a look at the example:

PREV     NEXT



Like it? Please Spread the word!