ベスパリブ

プログラミングを主とした日記・備忘録です。ベスパ持ってないです。

C++で文字列のスライス

C++全然わからない。

最近C++を使っているのですが、Pythonでいう文字列のスライスが使いたい。

s = "abcdef"
print(s[0:3])  # ==> "abc"

こんなの。

調べてもないっぽいのでそれっぽいものを実装。

#include <iostream>
#include <string>

using namespace std;

string str_slice(string s, int start, int end){
    if(end > s.size()){
        end = s.size();
    }
    if(end-start <= 0){
        return "";
    }
    return s.substr(start, end-start);
}

int main(void){
    string s = "abcdef";
    
    cout << str_slice(s, 0, 3) << endl;  // ==> "abc"
    cout << str_slice(s, 0, s.size()) << endl;  // ==> "abcdef"
    cout << str_slice(s, 0, 100) << endl;  // ==> "abcdef"
    cout << str_slice(s, 1, 0) << endl;  // ==> ""
    return 0;
}

start, endはint型でよいのだろうか。size_t型をよくわかっていない。 なるべくPythonっぽい挙動に似せた。Pythonはマイナス値取るけどあんまり使わないので実装していない。