未分類

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 で三角形の相似記号を入力する

\sim を使う。 例 $\triangle{ABC} \sim \triangle{DEF}$ 結果

no image

tex で⇔記号の上に文字を表示する方法

\underset を使って表示することができる。amsmath パッケージを使う。 例 \usepackage{amsmath} \begin{document} $\underset{\Leftr …

no image

C言語でchar文字列の長さを取得する (strlen)

strlen 関数を使って取得すればよい。sizeof という関数もあるが、strlen と振る舞いが異なるので注意。 例 #include<stdio.h> #include<strin …

no image

tex で脚注を表示する方法

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

no image

tex で打ち消し線を入力する方法

次のように入力すればよい。打ち消し線は、英語で strikethrough と呼ぶ。 例 \usepackage[normalem]{ulem} \begin{document} Good \sout …