[C++] 文字大文字小文字相互変換する方法 (std::string)

1 min read
hiroweb developer

前提

#include <string>
using namespace std;

方法

文字列を小文字に変換するには、std::transform関数を使用して、文字列の最初の文字から最後の文字までイテレートし、各文字を::tolower関数を使用して小文字に変換する必要がある。同様に、文字列を大文字に変換するには、::toupper関数を使用して大文字に変換する。

文字列をすべて小文字に変換する

#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

int main(){
  string str("ABCDEFG");

  transform(str.begin(), str.end(), str.begin(), ::tolower);

  cout << str << endl;

  return 0;
}

文字列をすべて大文字に変換する

#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

int main(){
  string str = "abcdefg";

  transform(str.begin(), str.end(), str.begin(), ::toupper);

  cout << str << endl;

  return 0;
}