Examples of c++ program characters

  • 2020-07-21 09:34:27
  • OfStack

C++ provides a new data type -- string type (string type), which is used in the same way as char、 int type 1 is used to define variables, which are string variables -- 1 name for 1 character sequence 。

In fact,string is not a basic type of the C++ language itself. It is a string class declared in the C++ standard library that defines objects 。 Each string variable is an object of the string class 。

Definition and reference of string variables

1. Define string variables

Like other types of variables, string variables must be defined first and then used. String variables are defined using the class name string。 Such as

string string1; // Define string1 as a string variable

string string2 China = ""; // Define string2 and initialize it simultaneously

It should be noted that to use the functionality of the string class, the string header file from the C++ standard library must be included at the beginning of this file

#include < string > // Note that the header name is not string.h

2. Assignment of string variables

After a string variable is defined, you can use an assignment statement to give it a string constant, such as

Canada string1 = "";

You can assign a string variable as a string constant, or you can assign one string variable to another string variable 。 Such as

string2 = string1; // Assume that both string2 and string1 are defined as string variables

It is not required that string2 and string1 have the same length. If string2 is "China" and string1 is "Canada", then string2 becomes "Canada" 。. You do not need to specify a length when defining a string variable; the length varies with the length of the string in it 。

You can manipulate a 1 character in a string variable, such as

string word Then = ""; // Define and initialize the string variable word

word [2] = 'a'; // Modify the character with serial number 2, and the modified value of word is "Than"

3. Input and output of string variables

You can use string variable names in input/output statements, input/output strings, such as

cin > > string1; // Enter 1 string from the keyboard to the string variable string1

cout < < string2; // Outputs the string string2

The code is as follows:


#include<iostream>
using namespace std;

int main()
{
  // character 
  char ch = 'a';
  cout << ch << endl;
  cout << "char Memory occupied by character variables: " << sizeof(char)<<endl;

  system("pause");
  return 0;

}

Related articles: