Today's error series: function substr intercepts a paragraph in string

Share the experience of today's string interception.

Share one, after intercepting a certain'substring' of string to the end

An example is like the title:
intercept all the strings after the string "I" in the string: "aaa bbb ccc, I love CSDN !".
[Although there is only one character'I' in the string in the example, the truth remains the same]

#include <iostream>
using namespace std;

int main()
{
    
    
	string str = "aaa bbb ccc , I love CSDN !";
	int pos = str.find("I"); // 在字符串str中找到字符串 "I" 出现的位置
	string str2 = str.substr(pos); // 在字符串str中,从"I" 出现的位置开始截取至结束
	cout <<"截取后的字符串为:" << str2.c_str() << endl;
}

Output:

截取后的字符串为:I love CSDN !

Summary: str.substr(pos); represents the string from the position of pos to the last bit of the string

Share two, intercept a certain segment of the string variable

An example is the title:
In the string: "aaa bbb ccc, I love CSDN !", 13 characters are intercepted from the 14th position.

#include <iostream>
using namespace std;

int main()
{
    
    

	string str = "aaa bbb ccc , I love CSDN !";
	string str2 = str.substr(14,13); // 14表示要截取的字符串的开始的位置,13代表要截取的字符串的长度。
	cout << "截取后的字符串为:" << str2.c_str() << endl;
}

Output:

截取后的字符串为:I love CSDN !

Summary: str.substr(pos, n); pos represents the starting position of the string to be intercepted, and n represents the length of the string to be intercepted.

Share three, supplement c_str()

It is estimated that the careful students found out that when outputting string, it is output like this

str2.c_str()

Why is .c_str added to the end?
Because if you don’t add it, it will report an error like this

错误	C2679	二进制“<<: 没有找到接受“std::string”类型的右操作数的运算符(或没有可接受的转换)

The reason is: String type does not have overload << symbol

So when outputting the string, it can be solved by calling the c_str() method.

Share four, supplement find()

Str.find("I"); is used in the share one above;

Returns the position of the first occurrence of the string "I"

End:

Sharing is also a way to deepen your understanding of the problem again. It may not be comprehensive, but it is definitely useful and will continue to be improved later~

Guess you like

Origin blog.csdn.net/hwx802746/article/details/112170506