未分類

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 で行内を結合する方法

\multicolumn を使って、結合する行の成分の数を指定することができる。次の例では「3」を指定して、結合している。 例 \begin{table} \begin{tabular}{ |c|c| …

no image

tex で同値記号(⇔)を入力する方法

同値記号を入力するには、\Leftrightarrow を使う。 例 $b \leftrightarrow c$, $b \Leftrightarrow c$

no image

c++ で文字列をファイルに保存する方法

result.txt というファイルに “data1 data2 data3” という内容を保存する。ofstream を使って書き出す。 例 #include<iost …

no image

matplotlib で x, y軸・タイトルのフォントサイズを調整する

ラベルの fontsize で指定する。 例 import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2, 100) …

no image

tex で脚注を表示する方法

\footnote を使う。 例 \footnote{this is a footnote.} 結果