0

文字列を小文字から大文字に、またはその逆に変換する単一の関数が c++ にありますか? 大文字と小文字を区別しない 2 つの文字列を比較する必要があり、一方の文字列しか変換できず、もう一方の文字列はそのままである必要があります。

4

3 に答える 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 に答える
0

以下を使用できます。

  • std::tolowerクリックしてstd::toupper クリックしてstd::transformクリック
  • ブースト、この質問のように
  • 質問で提案したように、単に文字列を反復処理します。文字列内のすべての文字を変換するには、それ繰り返し処理する必要があります。
于 2013-02-11T08:15:35.820 に答える