C++——string usage

Common construction interfaces of string 

string()

Construct an empty srting class object, empty string

string(const char* str)

initialize with string

string(const string& str) Copy construction, initialized using string class
string(size_t n, char c)  Initialized with n characters c
string s1; 
string s2("hello world");
string s3(s2); 
string s4(10,'*');

Capacity operations on string class objects

size Returns the effective length of the string
capacity Return the total space size
empty Determine whether the object is empty
clear Clear valid characters
reserve Reserve space for string
resize Modify the number of valid characters

size - returns the effective length of the string

std::string::size
size_t size() const;
int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.size() << " bytes.\n";
  return 0;
}
//The size of str is 11 bytes

 capacity - returns the total size of the space

std::string::capacity
size_t capacity() const;
int main ()
{
  std::string str ("Test string");
  std::cout << "size: " << str.size() << "\n";
  std::cout << "capacity: " << str.capacity() << "\n";
  return 0;
}

//size: 11
//capacity: 15

 empty - Determine whether the object is empty

std::string::empty
bool empty() const;

Application: Read and store the content entered by the user line by line until a blank line is encountered 

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string line;
	string content;
	do
	{
		getline(cin, line);
		content += line + '\n';
	} while (!line.empty());
	cout << content;
}

clear - Clear valid characters

std::string::clear
void clear();
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str("hello world");
	str.clear();
	if (str.empty())
		cout << "string has been deleted" << endl;
}

clear only clears the data and does not change the space size 

reserve - reserve space for a string

std::string::reserve
void reserve (size_t n = 0);
int main()
{
	string str("hello world");
	cout << str.capacity() << endl;
	cout << str.size() << endl;
	str.reserve(100);
	cout << str.capacity() << endl;
	cout << str.size() << endl;
}

 When the parameter n is smaller than the string size, the capacity will not be reduced

resize - modify the number of valid characters

std::string::resize
void resize (size_t n);void resize (size_t n, char c);

When n is larger than the string size, the extra space will be filled with the character c (\0 will not be overwritten) . If c is automatically filled with \0 by default; if n is smaller than the string size, the extra characters will be filled. Delete directly, but will not change the basic space capacity

int main()
{
	string str;
	str.resize(1);
	cout << str << endl;
	str.resize(5, '+');
	cout << str << endl;//字符串是 \0++++ 不同编译器输出可能不同
	str.resize(1);
	cout << str << endl;
}

Access and traversal of string class objects

operator[ ] Access by subscript, similar to an array
begin,end Iterator sequential traversal
rbegin,rend Iterator traverses in reverse order
rangefor The bottom layer is still an iterator
c_str Return c format string

operator[ ] ——operator overloading of [ ]

std::string::operator[]
char& operator[] (size_t pos);const char& operator[] (size_t pos) const;

The use is similar to that of an array, and both access the characters of the subscript position of the number in [ ]

int main()
{
	string str("hello world");
	for (int i = 0; i < str.size(); i++)
	{
		cout << str[i];
	}
	cout << endl;
}

Iterators begin and end , sequential traversal

iterator begin();const_iterator begin() const;
iterator end();const_iterator end() const;
using namespace std;

int main()
{
	string str("hello world");
	string::iterator sit = str.begin();
	while (sit != str.end())
	{
		cout << *sit;
		sit++;
	}
	cout << endl;
}

Iterators rbegin and rend , traverse in reverse order

reverse_iterator rbegin();const_reverse_iterator rbegin() const;
reverse_iterator rend();const_reverse_iterator rend() const;
using namespace std;

int main()
{
	const string str("hello world");
	string::const_reverse_iterator sit = str.rbegin();
	while (sit != str.rend())
	{
		cout << *sit;
		sit++;
	}
	cout << endl;
}

Range for (underlying iterator)

int main()
{
	const string str("hello world");
	for (char c : str)
	{
		cout << c;
	}
	cout << endl;
}

c_str - Returns a c format string

std::string::c_str

const char* c_str() const;
int main()
{
	string str("hello world");
	const char* ch = str.c_str();
	cout << ch << endl;
}

 This interface is for better compatibility with C language


Modification of string class objects

append append string
operator+=

append string

find Find the character (string) before and return the subscript position
rfind Find the character (string) from the end and return the subscript position
substr Extract substring from string

append - append a string

std::string::append
	
//追加str
string& append (const string& str);
	
//追加str的子串,字串是从str的subpos下标位置开始,向后的sublen个字符
string& append (const string& str, size_t subpos, size_t sublen);

//追加常量字符串s
string& append (const char* s);
	
//追加常量字符串的前n个字符
string& append (const char* s, size_t n);
	
//追加n个字符c
string& append (size_t n, char c);

//迭代器追加
template <class InputIterator>   string& append (InputIterator first, InputIterator last);
#include <iostream>
#include <string>

int main ()
{
  std::string str;
  std::string str2="Writing ";
  std::string str3="print 10 and then 5 more";

  // used in the same order as described above:
  str.append(str2);                       // "Writing "
  str.append(str3,6,3);                   // "10 "
  str.append("dots are cool",5);          // "dots "
  str.append("here: ");                   // "here: "
  str.append(10,'.');                    // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append(5,'.');                // "....."

  std::cout << str << '\n';
  return 0;
}
//Writing 10 dots here: .......... and then 5 more.....

operator+= - append string

std::string::operator+=
	
string& operator+= (const string& str);
	
string& operator+= (const char* s);
	
string& operator+= (char c);

The functions of += operator overloading and append are basically the same. In addition, append can use iterators to insert a specified number of characters, but += is more convenient to use.

find - Find the character (string) in the past and return the subscript position

std::string::find

size_t find (const string& str, size_t pos = 0) const;	
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (char c, size_t pos = 0) const;

rfind - search for a character (string) from the end and return the subscript position

string::npos is a static unsigned integer variable with size -1 (that is, the largest unsigned integer)

std::string::rfind

size_t rfind (const string& str, size_t pos = npos) const;	
size_t rfind (const char* s, size_t pos = npos) const;
size_t rfind (const char* s, size_t pos, size_t n) const;	
size_t rfind (char c, size_t pos = npos) const;

If rfind does not give the starting position of the search, or the starting position subscript is out of bounds, it will start searching from the end of the string; rfind, like find, will return npos if the target is not found.

substr - extract a substring from a string

std::string::substr
string substr (size_t pos = 0, size_t len = npos) const;

If pos is equal to the string size, an empty string will be returned; if pos is greater than the string size, an exception will be thrown.

#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

Non-member functions of string class

operator+ inefficient, use less
operator+= Append character (string)
operator>>,operator<< Input and output operator overloading

getline

get a line of string
relational operators size comparison

operator+

std::operator+ (string)

string operator+ (const string& lhs, const string& rhs);	

string operator+ (const string& lhs, const char*   rhs);
string operator+ (const char*   lhs, const string& rhs);

string operator+ (const string& lhs, char          rhs);
string operator+ (char          lhs, const string& rhs);

This function returns by value and requires deep copying. It is inefficient and should be used sparingly.

operator+= mentioned earlier

operator<<operator>>

Input and output operators are overloaded, very simple to use, and end when encountering a space or newline

getline - get a line of string

std::getline (string)

istream& getline (istream& is, string& str, char delim);//读到delim字符结束

istream& getline (istream& is, string& str);//读到'\n'结束

relational operators - size comparison

relational operators (string)

bool operator== (const string& lhs, const string& rhs);
bool operator== (const char*   lhs, const string& rhs);
bool operator== (const string& lhs, const char*   rhs);

bool operator!= (const string& lhs, const string& rhs);
bool operator!= (const char*   lhs, const string& rhs);
bool operator!= (const string& lhs, const char*   rhs);

bool operator<  (const string& lhs, const string& rhs);
bool operator<  (const char*   lhs, const string& rhs);
bool operator<  (const string& lhs, const char*   rhs);

bool operator<= (const string& lhs, const string& rhs);
bool operator<= (const char*   lhs, const string& rhs);
bool operator<= (const string& lhs, const char*   rhs);

bool operator>  (const string& lhs, const string& rhs);
bool operator>  (const char*   lhs, const string& rhs);
bool operator>  (const string& lhs, const char*   rhs);
	
bool operator>= (const string& lhs, const string& rhs);
bool operator>= (const char*   lhs, const string& rhs);
bool operator>= (const string& lhs, const char*   rhs);
#include <iostream>
#include <vector>

int main ()
{
  std::string foo = "alpha";
  std::string bar = "beta";

  if (foo==bar) std::cout << "foo and bar are equal\n";
  if (foo!=bar) std::cout << "foo and bar are not equal\n";
  if (foo< bar) std::cout << "foo is less than bar\n";
  if (foo> bar) std::cout << "foo is greater than bar\n";
  if (foo<=bar) std::cout << "foo is less than or equal to bar\n";
  if (foo>=bar) std::cout << "foo is greater than or equal to bar\n";

  return 0;
}

Guess you like

Origin blog.csdn.net/weixin_74269833/article/details/132512545