#include <iostream> #include <string> using std::cout; using std::endl; using std::cin; int main() { //文字列変数str1を宣言し"hello"で初期化! std::string str1 = "hello"; std::string str2 = "world"; std::string str3; str3 = str1 + ", " + str2 + "\n"; //ここでstr3をごにょごにょして //cout << str1 << ", " << str2 << endl; //", " ←これはダブルクォーテーションしてしまえば文字列 //"\n"←これもシングルクォートなら1文字だけど //ダブルクォーテーションなら文字列(1本でもニンジン理論) cout << str3; //で hello, world (改行)を表示してみよう cout << "str3の長さ:" << str3.length() << endl;; //for分でstr3の要素を1文字ずつ表示してみるよ for (int i = 0; i < str3.length(); i++) { cout << str3[i]; } //str3を1文字ずつチェックして、'o'が出てきたら'0'(ゼロ)と置き換えてみる //そんで表示する // 'o' → '0' // 'l' → '1' // 'd' → '6'とかもやってみて for (int i = 0; i < str3.length(); i++) { if (str3[i] == 'o') { str3[i] = '0'; } if (str3[i] == 'l') { str3[i] = '1'; } if (str3[i] == 'd') { str3[i] = '6'; } } cout << str3; //キーボードから入力した文字列に対して上の置き換えを行って表示! std::string str4; //キーボード入力の時はスペースで入力が途切れちゃうから注意! // スペースの代わりに"_"を入れちゃうといいよ "hello,_world" //キーボード入力のもできちゃったら、今度は文字列を反転してみよう! // "he110" → "011eh" 文字列の要素数に注意! length()でとれるのは文字数 return 0; }
std::string str4; //キーボード入力の時はスペースで入力が途切れちゃうから注意! // スペースの代わりに"_"を入れちゃうといいよ "hello,_world" cin >> str4; for (int i = 0; i < str4.length(); i++) { if (str4[i] == 'o') { str4[i] = '0'; } if (str4[i] == 'l') { str4[i] = '1'; } if (str4[i] == 'd') { str4[i] = '6'; } } cout << str4 << endl; //キーボード入力のもできちゃったら、今度は文字列を反転してみよう! // "he110" → "011eh" 文字列の要素数に注意! length()でとれるのは文字数 // str4.length()で入力された文字列の長さがわかるよ std::string str5 = ""; int ketu = str4.length() - 1; // i = i + 1 → i++ // i = i - 1 → i-- for (int i = str4.length() - 1; i >= 0; i = i - 1) { //cout << str4[i] << " "; str5 = str5 + str4[i]; } cout << str5 << endl;