C++におけるsubstr関数の定義と使い方(文字列からサブ文字列を取る)
4992 ワード
substr関数定義:
パラメータ:pos-最初の文字が存在する場所count-サブ文字列の長さ
戻り値:文字列に含まれるサブ文字列[pos,pos+count).
例外:std::out_of_range if pos > size()
substr( size_type pos = 0, size_type count = npos ) const;
パラメータ:pos-最初の文字が存在する場所count-サブ文字列の長さ
戻り値:文字列に含まれるサブ文字列[pos,pos+count).
例外:std::out_of_range if pos > size()
#include
#include
using namespace std;
int main()
{
string a = "0123456789abcdefghij";
//
string sub1 = a.substr(10);
cout << sub1 << '
'; //abcdefghij
// 5 ,
string sub2 = a.substr(5, 3);
cout << sub2 << '
'; //567
//
string sub4 = a.substr(a.size()-3, 50);
cout << sub4 << '
'; //hij
try {
// ,
string sub5 = a.substr(a.size()+3, 50);
cout << sub5 << '
';
} catch(const std::out_of_range& e) {
cout << "pos exceeds string size
";
}
}