Three ways to access strings in C + + summary _c language

Source: Internet
Author: User

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:

I Love china!

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:

I Love china!

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:

I Love china!

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:

Love china!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.