C++中string.find()関数とstring::npos
2149 ワード
文字列aがサブストリングbを含むかどうかを検索するにはstrAではない.find(strB)>0ではなくstrA.find(strB) != string:nposstring::size_type pos = strA.find(strB);if(pos != string::npos){}-------------------------------------------
int idx = str.find("abc");
if (idx == string::npos)
...
上記のコードでは、idxのタイプがintとして定義されています.これはエラーです.unsigned intとして定義しても間違っています.string::size_として定義する必要があります.type.
nposは次のように定義されています.
static const size_type npos = -1;
string::size_type(文字列構成器allocatorによって定義される)はsizeを記述するため、符号なし整数型である必要がある.デフォルトのコンフィギュレータは型別size_であるためtをsizeとしてtypeは,−1が符号なし整数型に変換され,nposもその型の最大符号なし値となる.実際の数値は型別size_にかかっていますtypeの実際の定義.残念なことに、これらの最大値は異なります.実際、(unsigned long)-1と(unsigned short)-1は異なる(両者の型別の大きさが異なることを前提とする).したがって、比較式idx==string::nposでは、idxの値が-1の場合、idxと文字列string::nposの型が異なるため、比較結果はfalseを得ることができる.
find()の結果がnposであるかどうかを判断するには、直接比較するのが最善です.
if (str.find("abc") == string::npos) { ... }
エラー:if(str.find(「abc」)
注意:abcが見つからないと-1が返され、0はTrueではありません.0はFalse
------------------------------------------------
説明:
1.string sub="abc";
string s = ”cdeabcigld“;
s.find(sub)、s.rfind(sub)の2つの関数は、完全に一致している場合に一致するインデックスを返します.すなわち、sにabcの3つの連続するアルファベットが含まれている場合に、現在のインデックスを返します.
s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub)の4つの関数は、sにsubの任意のアルファベットを含むインデックスを検索します.
2.クエリーがない場合はstring::nposを返します.これは大きな数で、その値は知る必要はありません.
int idx = str.find("abc");
if (idx == string::npos)
...
上記のコードでは、idxのタイプがintとして定義されています.これはエラーです.unsigned intとして定義しても間違っています.string::size_として定義する必要があります.type.
nposは次のように定義されています.
static const size_type npos = -1;
string::size_type(文字列構成器allocatorによって定義される)はsizeを記述するため、符号なし整数型である必要がある.デフォルトのコンフィギュレータは型別size_であるためtをsizeとしてtypeは,−1が符号なし整数型に変換され,nposもその型の最大符号なし値となる.実際の数値は型別size_にかかっていますtypeの実際の定義.残念なことに、これらの最大値は異なります.実際、(unsigned long)-1と(unsigned short)-1は異なる(両者の型別の大きさが異なることを前提とする).したがって、比較式idx==string::nposでは、idxの値が-1の場合、idxと文字列string::nposの型が異なるため、比較結果はfalseを得ることができる.
find()の結果がnposであるかどうかを判断するには、直接比較するのが最善です.
if (str.find("abc") == string::npos) { ... }
エラー:if(str.find(「abc」)
注意:abcが見つからないと-1が返され、0はTrueではありません.0はFalse
------------------------------------------------
////find size_type
string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");
string flag;
string::size_type position;
//find jk s
position = s.find("jk");
if (position != s.npos) // , c++ npos , npos 4294967295,
{
cout << "position is : " << position << endl;
}
else
{
cout << "Not found the flag" + flag;
}
//find flag s
flag = "c";
position = s.find_first_of(flag);
cout << "s.find_first_of(flag) is : " << position << endl;
// s 5 , b , b s
position=s.find("b",5);
cout<
説明:
1.string sub="abc";
string s = ”cdeabcigld“;
s.find(sub)、s.rfind(sub)の2つの関数は、完全に一致している場合に一致するインデックスを返します.すなわち、sにabcの3つの連続するアルファベットが含まれている場合に、現在のインデックスを返します.
s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub)の4つの関数は、sにsubの任意のアルファベットを含むインデックスを検索します.
2.クエリーがない場合はstring::nposを返します.これは大きな数で、その値は知る必要はありません.