1. Storing a string in a character array
Program 1: Define a character array and initialize it, and then output the string.
Copy Code code as follows:
#include <iostream>
using namespace Std;
int main () {
Char str[]= "I Lvoe china!";
cout<<str<<endl;
return 0;
}
Output results:
Copy Code code as follows:
STR is a character array name that represents the address of the first element of an array and, when it outputs str, starts with the character that the Str points to, outputting the characters one at a time until the ' yes ' is encountered.
2. Storing strings with string variables
Program 2: Define a string constant and initialize it, and then output the string it points to
Copy Code code as follows:
#include <iostream>
#include <string>
using namespace Std;
int main () {
String str= "I Lvoe china!";
cout<<str<<endl;
return 0;
}
Output results:
Copy Code code as follows:
3. Point to a string with the character pointer
Program 3: Define a character pointer variable and initialize it, and then output the string it points to.
Copy Code code as follows:
#include <iostream>
using namespace Std;
int main () {
Char *str= "I Lvoe china!";
cout<<str<<endl;
return 0;
}
Output results:
Copy Code code as follows:
Initializes the character pointer str, which in effect assigns the address of the first element in the string to Str.
Analysis:
Cout can either output characters from a string, or start with a pointer to a character, and output to the end of the string.
Copy Code code as follows:
#include <iostream>
using namespace Std;
int main () {
Char str[]= "I Lvoe china!";
cout<<&str[2]<<endl;
return 0;
}
Output results:
Copy Code code as follows: