 
 
 
 
 
 
 
  
string クラスについて一通り。 古い C++ のテキストでは文字列クラスを作ってみせるのが 定番という雰囲気もあったが (それどころか C 風の文字列の説明を 一所懸命している本もまだ珍しくはない)、 標準 C++ ライブラリィに含まれるようになったので、 もうその利用方法を学ぶ時期でしょう。
| string1.C | 
| #ifdef __FreeBSD__
#include <iostream.h>
#else
#include <iostream>
#endif
#include <string>
using namespace std;
void add_newline(string &s)
{
  s += '\n';
}
int main()
{
  // string に文字列リテラルを代入できる
  string s1 = "Hello";
  string s2 = "world";
  // string は + 演算子で、string, 文字列リテラル, 文字を結合できる
  string s3 = s1 + ", " + s2 + '!';
  add_newline(s3);
  cout << s3;
  // string 同士、string と文字列リテラルは == で比較できる
  if (s3 == "Hello, world!\n")
    cout << "Equal" << endl;
  // C 形式の文字列は c_str() メンバ関数で得られる。
  cout.form("%s\n", s1.c_str());
  // 一行丸々入力するには getline()
  string line_input;
  cout << "input a line" << endl;
  getline(cin, line_input);
  cout << "入力された行は" << line_input << endl;
}
 | 
| string1.out | 
| mathpc00% ./test-string1 Hello, world! Equal Hello input a line To be to be, ten made tobe! 入力された行はTo be to be, ten made tobe! mathpc00% | 
| test-string1.C | 
| #include <iostream.h>
#include <string>
int main()
{
  string s1 = "aa";
  string s2("bb");
  string s3;
  s3 = s1 + s2;
  cout << s1 << endl;
  cout << s2 << endl;
  cout << s3 << endl;
  for (int i = 0; i < 5; i++)
    s3 += s3;
  cout << s3 << endl;
  for (size_t i = 0; i < s3.length(); i++)
    cout << s3[i];
  cout << endl;
  // 部分文字列について
  s3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  cout << '"' << s3 << '"' << "という文字列について" << endl;
  string first10(s3, 0, 9);
  string cut_first10(s3, 10);
  cout << "最初の10文字" << first10 << endl;
  cout << "最初の10文字をカット" << cut_first10 << endl;
  return 0;
}
 | 
 
 
 
 
 
 
