One of the foremost useful data types supplied within the C++ libraries is that the string. A string may be a variable that stores a sequence of letters or other characters, like “Steve” or “The full name is Steve Oualline!”.

 A bit like the opposite data types, to make a string we first declare it, then we will store a worth in it. Strings are arrays of characters. The special character ‘ ’ (NUL) is used to indicate the end of a string.

Example

char name[4];
main ()
{
name[0] = 'S';
name[1] = 'a';
name[2] = 'm';
name[3] = '';
return (0);
}

This creates a character array four elements long. Note that we had to allocate one character for the end-of-string marker.

String constants consist of text enclosed in double quotes (“). You may have already noticed that we’ve used string constants extensively for output with the cout standard class.

C++ does not allow one array to be assigned to another, so you can’t write an assignment of the form:

name = "Sam"; // Illegal

Instead you must use the standard library function strcpy to copy the string constant into the variable.

(strcpy copies the whole string including the end-of string character.) To initialize
the variable name to “Sam” you would write:

#include<string.h>

 char name[4];

 main() { 

strcpy(name, "Sam"); // Legal 

return (0); }

The line #include<string.h> is needed to inform C++ that you are using the string function library.

How C++ uses variable-length In strings

#include<string.h>

char string[50]; // variable-length strings

main()
{

strcpy(string, "Sam");

creates an array (string) that can contain up to 50 characters. The size of the array is 50, but the length of the string is 3. Any string up to 49 characters long can be stored in string. One character is reserved for the NULL that indicates the end of the string.

This article is written by our awesome writer
Comments to: What is string in Cpp with example

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password