Cplusplus-cpp-strings

提供:Dev Guides
移動先:案内検索

C ++文字列

C ++は、次の2種類の文字列表現を提供します-

  • Cスタイルの文字列。
  • 標準C ++で導入された文字列クラスタイプ。

Cスタイルの文字列

Cスタイルの文字列は、C言語内で作成され、C ++内で引き続きサポートされます。 この文字列は、実際には null 文字「\ 0」で終了する文字の1次元配列です。 したがって、nullで終わる文字列には、 null が後に続く文字列を構成する文字が含まれます。

次の宣言と初期化により、「Hello」という単語で構成される文字列が作成されます。 配列の末尾にヌル文字を保持するために、ストリングを含む文字配列のサイズは、「Hello」という単語の文字数よりも1つ多くなります。

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

あなたが配列の初期化のルールに従う場合は、次のように上記のステートメントを書くことができます-

char greeting[] = "Hello";

以下は、C/C ++で上記で定義された文字列のメモリ表示です-

C/C ++の文字列表示

実際には、文字列定数の末尾にヌル文字を配置しません。 C ++コンパイラは、配列を初期化するときに、文字列の末尾に「\ 0」を自動的に配置します。 上記の文字列を印刷してみましょう-

#include <iostream>

using namespace std;

int main () {

   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

   cout << "Greeting message: ";
   cout << greeting << endl;

   return 0;
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Greeting message: Hello

C ++は、nullで終わる文字列を操作する幅広い機能をサポートしています-

Sr.No Function & Purpose
1

strcpy(s1, s2);

文字列s2を文字列s1にコピーします。

2

strcat(s1, s2);

文字列s2を文字列s1の末尾に連結します。

3

strlen(s1);

文字列s1の長さを返します。

4

strcmp(s1, s2);

s1とs2が同じ場合は0を返します。 s1 <s2の場合、0未満。 s1> s2の場合、0より大きい。

5

strchr(s1, ch);

文字列s1に最初に現れる文字chへのポインターを返します。

6

strstr(s1, s2);

文字列s1内で文字列s2が最初に現れる場所へのポインタを返します。

次の例では、上記の機能のいくつかを利用しています-

#include <iostream>
#include <cstring>

using namespace std;

int main () {

   char str1[10] = "Hello";
   char str2[10] = "World";
   char str3[10];
   int  len ;

  //copy str1 into str3
   strcpy( str3, str1);
   cout << "strcpy( str3, str1) : " << str3 << endl;

  //concatenates str1 and str2
   strcat( str1, str2);
   cout << "strcat( str1, str2): " << str1 << endl;

  //total lenghth of str1 after concatenation
   len = strlen(str1);
   cout << "strlen(str1) : " << len << endl;

   return 0;
}

上記のコードをコンパイルして実行すると、次のような結果が生成されます-

strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

C ++の文字列クラス

標準C ++ライブラリは、上記のすべての操作をサポートする string クラスタイプを提供し、さらに多くの機能を提供します。 私たちは次の例をチェックしましょう-

#include <iostream>
#include <string>

using namespace std;

int main () {

   string str1 = "Hello";
   string str2 = "World";
   string str3;
   int  len ;

  //copy str1 into str3
   str3 = str1;
   cout << "str3 : " << str3 << endl;

  //concatenates str1 and str2
   str3 = str1 + str2;
   cout << "str1 + str2 : " << str3 << endl;

  //total length of str3 after concatenation
   len = str3.size();
   cout << "str3.size() :  " << len << endl;

   return 0;
}

上記のコードをコンパイルして実行すると、次のような結果が生成されます-

str3 : Hello
str1 + str2 : HelloWorld
str3.size() :  10