Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the String class in C++

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to use the String class in C++, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something from this article.

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 with a known string using the copy constructor

String str21 = str1

String str2 = ("Hello World!")

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

S.empty () / / determines whether the string s is empty

S.size () / / gets the size of the string s

S1 = = S2 / / compare whether the string S1 equals the string S2

S1 + 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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report