cからc++への変換(二)

10145 ワード

私はC++を勉強している同級生で、自分の学習ノートと自分の理解を記録しています.何か間違ったところがあったら、友达に指摘してほしいです.私が書いたのはc言語の基礎があってからC++を勉強した経験です.ゼロベース学習C++ではありません.
5.文字列
c言語には文字列変数はなく,文字配列で表される.そしてc言語の文字列には2つの大きな標識があります.1、文字列ヘッダアドレス2、終了フラグ'0'.ここではcスタイル文字列と呼びます.まず、Cスタイルの文字列に何か処理があることを思い出します.ある文字を取得したり、値をつけたり、比較したり、接続したり、長さを計算したりする操作があるでしょう.同じC++の文字列もあります.もちろん操作は簡単です.まずC++文字列の使用にはヘッダファイルstringを含める.注意はstringではありません.h. 以下、C言語における文字列の処理と比較してC++の文字列処理を書きます.
  • (1)文字列の定義.C言語:char a[20]=「hello,world」;char *a=“hello,world”; C++:stringオブジェクトstring a="hello,world";string b(“hello,world”); string c(b); ここで、Cスタイルの文字列は、宣言時に初期化されていない場合は、文字配列に値を割り当てるにはstrcpy関数が必要です.でもC++は使いません.分離を宣言および初期化できます.
  • #include 
    #include 
    
    using namespace std;
    
    int main()
    {
    	string a = "hello,world";//  string  
    	string b("hello,world");//  string  
    	string c;//  string  
    	c="hello,baby";
    	cout<<s1<<endl;
    	cout<<s2<<endl;
    	cout<<s3<<endl;
    }
    
  • (2)stringオブジェクトはCスタイル文字列
  • に変換できる.
    フォーマット出力、例えばsprintfを使用する必要がある場合があります.このときはCスタイルの文字列を使わなければならないのでstringをCスタイルの文字列に変換しなければなりません.ここでstringのメンバー関数c_を呼び出します.str()でできます.
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
    	string s1 = "hello world";
    	char buf[100];
    	sprintf(buf, "s1 = %s", s1.c_str());
    	cout<<buf<<endl;
    }
    
  • (3)文字列コピー、比較、接続
  • #include
    #include
    
    using namespace std;
    
    int main()
    {
    	string s1="hello,world";
    	string s2="hello,worle";
    	string s3="hello,baby";
    	
    	s3=s2;//  ,C  strcpy    
    	s3+=s2;//  ,C  strcat    。    string  string。
    	//           ,  sprintf。
    	
    	if(s2>s1)//  ,strcmp    。            。
    	{
    		cout<<s2<<endl;
    	}
    }
    
  • (4)文字列サイズメンバー関数s.empty()を取得して、空であるか否かを判断する.メンバー関数s.size()は、strlenと同じ文字列長を取得します.
  • #include 
    #include 
    
    using namespace std;
    
    int main()
    {
    	string s = " ";
    	cout<<s.empty()<<endl;//0     
    	
    	string s2 = "";
    	cout<<s2.empty()<<endl;//1    
    
    	string s3 = "hello world";
    	cout<<s3.size()<<endl;
    }
    
  • (5)その他の注意事項1.cinで文字列を入力する場合は、スペースを入力できません.スペースを入力するにはgetline(cin,s)を使用します.2.文字列を取得する要素はCスタイル文字列と同じです.sring s=“hello,world”;s[i]取得文字要素
  • 6.boolタイプ
    C++はC言語より基本データ型boolタイプが1つ多い.boolタイプにはtrueとfalseの2つの値しかなく、真偽を表します.サイズは1バイトです.
    #include
    
    using namespace std;
    
    int main()
    {
    	bool gender=ture;
    	cout<<gender? boy:girl<<endl;//    
    	cout<<boolalpha<<gender<<endl;//   boolalpha
    	//   bool         true  false      1  0
    }