文字列を小文字から大文字に、またはその逆に変換する単一の関数が c++ にありますか? 大文字と小文字を区別しない 2 つの文字列を比較する必要があり、一方の文字列しか変換できず、もう一方の文字列はそのままである必要があります。
3 に答える
4
std::toupper
またはstd::tolower
を と組み合わせて使用できます。std::for_each
std::transform
#include <cctype>
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
std::string s = "Hello, World!";
std::transform(s.begin(), s.end(), s.begin(), [](char c) {return std::toupper(c);});
std::cout << s << "\n";
}
編集
大文字と小文字を区別しない 2 つの文字列を比較する必要があり、一方の文字列しか変換できず、もう一方の文字列はそのままである必要があります。
大文字と小文字を区別せずに 2 つの文字を比較する関数を定義して、次のように使用できますstd::equal
。
bool case_insensitive_comp(char lhs, char rhs)
{
return std::toupper(lhs) == std::toupper(rhs);
}
int main()
{
std::string s1 = ....;
std::string s2 = ....;
bool match = std::equal(s1.begin(), s1.end(), s2.begin(), case_insensitive_comp);
}
を呼び出す前に、文字列の長さが同じであることを確認する必要がある場合がありますstd::equal
。
于 2013-02-11T08:14:32.653 に答える
1
std::toupperまたはstd::tolowerで std ::transformを使用できます
std::string s("hello, world!");
std::transform(s.begin(), s.end(), s.begin(), (int (*)(int))std::toupper);
于 2013-02-11T08:15:11.203 に答える