C++ study notes string articles

1. Connection string +

string str1 = "hello";
string str2 = "world";
string str = str1 + str2;// "helloworld"

2. Find find()

  1. If a match is found, return the subscript
  2. No matches found, returnstring::npos

For example:

string str = "how are you";
int pos = str.find("are"); // 返回 4
	pos = str.find("was"); // 返回 string::npos
if (pos!=string::npos)
	printf("Found, pos = %d\n", pos);
else 
	printf("Not found!\n");

3. Delete the specified element erase() + remove()

You cannot remove an element from a sequence without knowing the specific scenario, that is, what container the element is stored in. So "element-removing" algorithms can't do that either, they just rewrite selected elements or ignore copied elements. The removal operation does not change the number of elements in the sequence of the "removed" element. So we also need to use erase()to change the number of sequence elements to achieve the purpose of deletion!

// 删除str中的 'a' 元素
// 需要 #include <algorithm>
// 写法1
	str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());
// 写法2
	string::iterator it = std::remove(str.begin(), str.end(), 'a');
	str.erase(it, str.end());
  1. The first step remove(string::iterator begin, string::iterator end, char ch);
    returns an iterator. If n a’s are deleted, the iterator at the last nth position is returned
  2. The second step str.erase(string::iterator begin, string::iterator end);is to delete the unnecessary characters at the end to actually remove the specified element.

4. Output content

// 方法1
for (unsigned int i=0; i<str.size(); ++i)
{
    
    
	printf("%c", str[i]);
}
// 方法2
for (string::iterator it = str.begin(); it!=str.end(); ++it)
{
    
    
	printf("%c", *it);
}

5. Some points to note begin() end() size() empty()

bool empty() const noexcept
{
    
    	// test if sequence is empty
		return (size() == 0);
}
string str = "12345";
str.begin();	 // 0
str.end();		 // 6 最后一个有效位+1
str.size();		 // 6 最后一个有效位+1

Guess you like

Origin blog.csdn.net/weixin_45827203/article/details/129651475