[C++] 標準文字列処理

  情報系, プログラミング, C++

文字列処理

C++では,文字列を扱う方法が2つあり,1つはC言語と同様に「char型配列」を使用する方法,もう1つは「string」ライブラリを使用した方法である.


string型

C++では,標準で「string型」が用意されている.string型を使用するには,「string」をincludeする必要がある.

#include <iostream>
#include <string>
int main()
{
    std::string str1;         // 文字列型の宣言
    std::string str2("abc");  // 文字列型の宣言して、「abc」で定義
    std::string str3(5,'a');  // 文字列型の宣言して、'a'を5個格納したものを定義
    std::string str4="efg";   // 文字列型の宣言して、「efg」で定義
  
    std::cout << str2 << std::endl;
    std::cout << str3 << std::endl;
    std::cout << str4 << std::endl;
}

文字列操作

string型では,char型配列による文字列と同様にして,文字列の操作ができる.

#include <iostream>
#include <string>
int main()
{
    std::string str="0123456789";
  
    string str1 = str[0];   // str1に「0」が格納される。
    str1[5]='A';            // 「01234A6789」になる。
  
    std::cout << str << std::endl;
    std::cout << str1 << std::endl;
}

文字列結合

string型では,演算記号の「+」を用いることで結合することができる.

#include <iostream>
#include <string>
int main()
{
    std::string str1="abc";
    std::string str2="def";
    std::string str3=str1+str2;       // 「abcdef」がstr3に格納される。
    std::cout << str3 << std::endl;
}

文字列挿入

string型では,insertメソッドを用いることで文字列を挿入することができる.

#include <iostream>
#include <string>
int main()
{
    std::string str1="Ho";
    std::string str2="rld";
  
    // 変数.insert(i,str);    // i+1文字目にstrを挿入
    str1.insert(1,"ell");     // str1がHelloになる
    str2.insert(0,"Wo");      // str2がWorldになる
  
    std::cout << str1 << std::endl;
    std::cout << str2 << std::endl;
}

文字列抽出

string型では,substrメソッドを使用することで,任意の場所の文字列を抽出することができる.

#include<iostream>
#include<string>
int main()
{
    std::string str="abcdefghijklmn";
  
    // 変数.substr(i,j);               // 変数のi+1文字目からj文字抽出
    std::string str2=str.substr(1,3); // 「bcd」が抽出される
  
    // 変数.substr(i);                // 変数のi+1文字目以降を抽出
    std::string str3=str.substr(5);   // 「fghijklmn」が抽出される
  
    std::cout << str2 << std::endl;
    std::cout << str3 << std::endl;
}

文字列長取得

string型では,「length」メソッドもしくは「size」メソッドをすることで格納されている文字列長を取得することができる.

#include <iostream>
#include <string>
int main()
{
    std::string str="hello world";
  
    // 文字列長を取得
    int length=str.length();  // lengthに11が格納される。
    int size=str.size();      // sizeに11が格納される。
  
    std::cout << length << std::endl;
    std::cout << size << std::endl
}

数値から文字列変換

C++では,数値を文字列に変換するための関数として「to_string」関数がある.

#include <iostream>
#include <string>
int main()
{
    int i=123;
  
    string str=std::to_string(i);   // strに文字列の「123」が格納される。
    std::cout << str << std::endl;
}

LEAVE A COMMENT