未分類

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

投稿日:

length() で取得する。

#include <iostream>
#include <string>

using namespace std;
int main ()
{
string str1 = "Good morning";
cout << str1.length() << endl;
return 0;
}

結果

12

参考

上記のコードでは、バイト数を取得している。
全角文字列の場合には、注意が必要。

-未分類

執筆者:


comment

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

関連記事

no image

python3 で、指定した文字が最後に現れる場所を取得する

rfind を使うと、指定した文字が最後に現れる場所(インデックス)を取得することができる。 例 str1 = “12345abab” result = str1.rfind(“ab”) print( …

no image

tex で行の色を1行ごとに交互につける

色を1行ごとに交互につけるには、\xcolor パッケージを使った上で、\rowcolors コマンドを使って色を指定する。 例 \usepackage[table]{xcolor} \begin{d …

no image

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

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

no image

python3 で、文字列の末尾の文字を削除する方法

[:-1] で、最後の文字を取り除いた文字列を取得することができる。 例 str1 = “こんにちは。” result = str1[:-1] print(result) 結果 こんにちは

no image

matplotlib で x軸・y軸ラベルをつける

plt.xlabel と plt.ylabel を使う。 例 import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, …