代码之家  ›  专栏  ›  技术社区  ›  rawwar

如何在c++[duplicate]中执行python风格的字符串切片

  •  1
  • rawwar  · 技术社区  · 7 年前

    有可能实现一种方法,通过它我可以在C++中使用切片 : 接线员。

    char my_name[10] {"InAFlash"};
    

    我是否可以实现函数或重写任何内部方法以执行以下操作:

    cout << my_name[1:5] << endl;
    

    nAFl

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string my_name;
        my_name = "Hello";
        // strcpy(my_name[2,5],"PAD");
        // my_name[2]='p';
        cout << my_name[2:4];
        return 0;
    } 
    

    但是,出现了以下错误

    helloWorld.cpp: In function 'int main()':
    helloWorld.cpp:10:22: error: expected ']' before ':' token
         cout << my_name[2:4];
                          ^
    helloWorld.cpp:10:22: error: expected ';' before ':' token
    
    3 回复  |  直到 7 年前
        1
  •  2
  •   Yuushi    7 年前

    substr :

    std::string my_name("InAFlash");
    std::string slice = my_name.substr(1, 4); // Note this is start index, count
    

    std::string_view (C++ 17)将是一条出路:

    std::string view slice(&my_name[0], 4);
    
        2
  •  3
  •   YSC    7 年前

    如果你被C型数组困住了, std::string_view (C++17) char[] 无需复制内存:

    #include <iostream>
    #include <string_view>
    
    int main()
    {
        char my_name[10] {"InAFlash"};
        std::string_view peak(my_name+1, 4);
        std::cout << peak << '\n'; // prints "nAFl"
    } 
    

    演示: http://coliru.stacked-crooked.com/a/fa3dbaf385fd53c5


    std::string ,则需要一份副本:

    #include <iostream>
    #include <string>
    
    int main()
    {
        char my_name[10] {"InAFlash"};
        std::string peak(my_name+1, 4);
        std::cout << peak << '\n'; // prints "nAFl"
    } 
    

    演示: http://coliru.stacked-crooked.com/a/a16112ac3ffcd8de

        3
  •  1
  •   schorsch312    7 年前

    如果你使用 std::string (C++方式)你可以

    std::string b = a.substr(1, 4);
    
    推荐文章