未分類

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

c言語で文字をつなげる方法

sprintf 関数を使って、result 変数に文字列 s1 と文字列 s2 を結合した文字列を出力することができる。 例 #include<stdio.h> int main(void) { …

no image

tex で脚注を表示する方法

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

no image

tex で文字列を変数として設定する方法

\newcommand を使って指定する。入力の数は自由に指定できる。 例 \newcommand{\variable}[2]{Hello #1. Good #2.} \variable{Taro}{ …

no image

python で文字列の長さを表示する方法

len を使う。 例 length = len(‘文字列あいうえお’) print(str(length)) 結果 8

no image

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

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