浅学C++的substr

#include<string>
#include<iostream>
using namespace std;
int main()
{
  string s("HIJKLMNOPQ");
  string a = s.substr(0,5);     //获得字符串s中从第0位开始的长度为5的字符串
  cout << a << endl;
    string b = s.substr(4,5);	 //获得字符串s中从第4位开始的长度为5的字符串
    cout << b << endl;
}

 

#include <string>
#include <iostream>

int main()
{
	using namespace std;

	string  str1("Heterological paradoxes are persistent.");
	cout << "The original string str1 is: \n " << str1
		<< endl << endl;

	basic_string <char> str2 = str1.substr(6, 7);			//从下标为6的字符开始截取7个字符
	cout << "The substring str1 copied is: " << str2
		<< endl << endl;

	basic_string <char> str3 = str1.substr();				//无参默认全部
	cout << "The default substring str3 is: \n " << str3
		<< "\n which is the entire original string." << endl;
}

输出结果:

The original string str1 is:
 Heterological paradoxes are persistent.

The substring str1 copied is: logical

The default substring str3 is:
 Heterological paradoxes are persistent.
 which is the entire original string.

猜你喜欢

转载自blog.csdn.net/qq_37592750/article/details/82828832