未分類

c++ で文字列(string)の foreach 操作を行う方法

投稿日:

string の各文字に対して操作を行うには、「iterator」(イテレータ)を使ってループを作る方法がある。

iterator の変数名は、it としておくと分かりやすい。

#include<iostream>

int main () {

std::string str1 = "good morning.";
for(std::string::iterator it = str1.begin(); it != str1.end(); ++it) {
std::cout << "*it=" << *it << std::endl;
}
return 0;
}

結果

*it=g
*it=o
*it=o
*it=d
*it=
*it=m
*it=o
*it=r
*it=n
*it=i
*it=n
*it=g
*it=.

-未分類

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

tex でインテグラルが小さくなる→大きくする方法

文章中でインテグラル(積分記号)を大きくするには、\displaystyle と書けばよい。 例 usual $\int \frac{ax+b}{cx+d} dx$display style $\di …

no image

python3 で特定のデータが含まれる行を削除する

data.txt からの入力から、「4 5 6」というデータがある行を削除して、output.txt に出力する。(データの各行の最後に \n があることに注意。) 例 f = open(‘data. …

no image

python3 でクラスの初期化を __init__ で行う

python でクラスのオブジェクトを生成したとき、__init__ メソッドが呼び出される(コンストラクタ)__init__ の引数には自身(self)を指定することが通例。一方、オブジェクト破棄の …

no image

matplotlib で縦横の罫線を出力する

罫線を出力するには、pyplot.grid を使う。 例 import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2 …

no image

c++ で文字列(string)の長さを取得する方法

length() で取得する。 例 #include <iostream> #include <string> using namespace std; int main () { str …