C++読書ノート:文字列
C++は、次の2種類の文字列表現を提供します.
Cスタイル文字列C++導入stringクラスタイプ
Cスタイル文字列Cスタイルの文字列はC言語に起源し、C++でサポートされ続けている.文字列は、実際にはnull文字0で終了する1次元文字配列です.したがってnullで終わる文字列には、文字列を構成する文字が含まれています.
次の宣言と初期化はRUNOOB文字列を作成します.配列の末尾に空の文字が格納されているため、文字配列の大きさは単語RUNOOBの文字数より1つ多い.(0は終端記号で、文字列の長さを求めることが多い)
char site[7] = {‘R’, ‘U’, ‘N’, ‘O’, ‘O’, ‘B’, ‘\0’}; 配列初期化規則に基づいて、上の文を次の文に書くことができます.
char site[] = “RUNOOB”;(一定長のない文字列を初期化)
上記のコードがコンパイルおよび実行されると、次の結果が得られます.
単語:RUNOOB
nullで終わる文字列の関数:1 strcpy(s 1,s 2);文字列s 2を文字列s 1にコピーします.
2 strcat(s1, s2); 文字列s 2を文字列s 1の末尾に接続します.接続文字列には、string str 1=「runoob」などの+番号も使用できます.string str2 = “google”; string str = str1 + str2;
3 strlen(s1); 文字列s 1の長さを返します.
4 strcmp(s1, s2); s 1とs 2が同じである場合、0を返します.s 1 s 2の場合、戻り値は0より大きい.
5 strchr(s1, ch); 文字列s 1の文字chの最初の出現位置を指すポインタを返します.
6 strstr(s1, s2); 文字列s 1の文字列s 2の最初の出現位置を指すポインタを返します.
C++のStringクラスC++標準ライブラリはstringクラスタイプを提供します
Cスタイル文字列C++導入stringクラスタイプ
Cスタイル文字列Cスタイルの文字列はC言語に起源し、C++でサポートされ続けている.文字列は、実際にはnull文字0で終了する1次元文字配列です.したがってnullで終わる文字列には、文字列を構成する文字が含まれています.
次の宣言と初期化はRUNOOB文字列を作成します.配列の末尾に空の文字が格納されているため、文字配列の大きさは単語RUNOOBの文字数より1つ多い.(0は終端記号で、文字列の長さを求めることが多い)
char site[7] = {‘R’, ‘U’, ‘N’, ‘O’, ‘O’, ‘B’, ‘\0’}; 配列初期化規則に基づいて、上の文を次の文に書くことができます.
char site[] = “RUNOOB”;(一定長のない文字列を初期化)
#include
using namespace std;
int main ()
{
char site[7] = {
'R', 'U', 'N', 'O', 'O', 'B', '\0'};
cout << " : ";
cout << site << endl;
return 0;
}
上記のコードがコンパイルおよび実行されると、次の結果が得られます.
単語:RUNOOB
nullで終わる文字列の関数:1 strcpy(s 1,s 2);文字列s 2を文字列s 1にコピーします.
2 strcat(s1, s2); 文字列s 2を文字列s 1の末尾に接続します.接続文字列には、string str 1=「runoob」などの+番号も使用できます.string str2 = “google”; string str = str1 + str2;
3 strlen(s1); 文字列s 1の長さを返します.
4 strcmp(s1, s2); s 1とs 2が同じである場合、0を返します.s 1 s 2の場合、戻り値は0より大きい.
5 strchr(s1, ch); 文字列s 1の文字chの最初の出現位置を指すポインタを返します.
6 strstr(s1, s2); 文字列s 1の文字列s 2の最初の出現位置を指すポインタを返します.
C++のStringクラスC++標準ライブラリはstringクラスタイプを提供します
#include
#include //
using namespace std;
int main ()
{
string str1 = "runoob";
string str2 = "google";
string str3;
int len ;
// str1 str3
str3 = str1; //
cout << "str3 : " << str3 << endl;
// str1 str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// ,str3
len = str3.size();// size
cout << "str3.size() : " << len << endl;
return 0;
}