プログラミング言語

C++ / 10

22 コメント
views
0 フォロー
10
とくに 2020/07/02 (木) 19:10:52 修正

C言語のコード

#include <stdio.h>

int main(){
   char *str1 = "Hello,World!"; //文字列の定義
   printf("%s\n",str1); //文字列を表示
   char *str2 = "Hello,World!";
   if(strcmp(str1,str2) == 0){ //文字列の比較
       printf("文字列は一致\n");
   }else{
       printf("文字列は不一致\n");
   }

   char str3[16];
   strcpy(str3,str1); //文字列のコピー(十分なメモリを確保しておかないとここでバッファオーバーランが発生。)
   printf("%s\n",str3); //Hello,World!

   char str4[64];
   strcpy(str4,"abcdef");
   strcat(str4,"ghijkl"); //文字列の連結
   printf("%s\n",str4); //abcdefghijkl
   return 0;
}

C++のコード(std:stringを使用)

#include <iostream>
#include <string> //std::stringを使う為に必要
using namespace std;

int main(){
    string str1 = "Hello,World!"; //文字列の定義
    cout << str1 << endl; //オペレータ<<がオーバーロードされている為、普通にcoutで表示できる。
    string str2 = "Hello,World!";
    if(str1 == str2){ //文字列の比較オペレータ==が定義されているので比較可能。
        cout << "文字列は一致" << endl;
    }else{
        cout << "文字列は不一致" << endl;
    }

    string str3;
    str3 = str1; //文字列のコピー。オペレータ=が定義されているので可能。
    cout << str3 << endl; //Hello,World!

    string str4 = "abcdef"; //初期化も可能
    str4 += "ghijkl"; //文字列の連結オペレータ+=が定義されているので可能。str4 = str4 + "ghijkl";でもできる。
    cout << str4 << endl; //abcdefghijkl
    return 0;
}
通報 ...