文字配列内の単語の位置を見つけて、その単語を別の単語に置き換えるにはどうすればよいでしょうか?
3772 次
1 に答える
1
文字配列を使用する代わりに、 を使用することをお勧めしstd::string
ます。これにより、実際の検索と置換を行うロジックを実装する必要がなくなり、新しい文字列が大きくなった場合にバッファ管理が行われる可能性がなくなります。文字列内の要素を検索および置換std::string
するためのメンバー関数が含まれています。
#include <string>
#include <iostream>
int main()
{
std::string haystack = "jack be nimble jack be blah blah blah";
static const std::string needle = "nimble";
std::cout << "before: " << haystack << std::endl;
// Find the word in the string
std::string::size_type pos = haystack.find(needle);
// If we find the word we replace it.
if(pos != std::string::npos)
{
haystack.replace(pos, needle.size(), "drunk");
}
std::cout << "after: " << haystack << std::endl;
}
これにより、次の出力が生成されます
前:ジャックは機敏にジャックは何とか何とか
後:ジャックは酔ってジャックは何とか何とか
于 2013-06-21T20:56:12.913 に答える