Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the String class in C++

Shulou Source: shulou.com Published: 2022-06-01 19:41:58 09月28日 Update

This article is about how to use the String class in C++. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

String Typ

Flipping through the books and reading all kinds of articles, I feel that there is nothing to say about String, so let's go over it briefly for a while.

1. The string in C++ is different from the string in C

There is no concept of string in C language, it is actually an array of characters, but there is a header file "string.h" in C, which provides function interfaces such as string concatenation, copy, comparison and so on. String in C++ is a string class, so you need to include the string header file when using it. Since string is a class under the std namespace, you also need to introduce the std namespace. Here is the sample code:

# include using std::string

2. Definition and initialization of string object in C++.

The string class in C++ provides several ways to initialize a string object:

String str1; / / default initialization, str1 is an empty string string str2 (str1); / / initialize string str21 = str1;string str2 = ("HelloWorld!") with a known string using the copy constructor; string str3 ("HelloWorld")

3. The operator of C++ string object (take the string s as an example)

Os > s / / write the input stream to s getline (is S) / / read a line from is to s.empty () / / determine whether the string s is empty s.size () / / get the size of the string s = = S2 / / compare whether the string S1 is equal to the string s2s1 + S2 / / concatenate the strings S1 and S2 into a new amount string

Read input from the command line and save to a string:

# include int main () {std::string line; while (getline (cin, line)) if (line.size () > 1024) cout

Tags: Characters strings clocked characters objects files letters contents functions size copies numbers articles methods more space equivalence articles input good Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Information OPPO Reno Docker Apple