如何在 C++ 中进行 python 样式的字符串切片
How to do python style string slicing in c++
是否可以实现一种方法,通过该方法我可以使用 :
运算符在 C++ 中进行切片。
比如我定义了一个C风格的字符串,如下所示:
char my_name[10] {"InAFlash"};
我能否实现一个函数或覆盖任何内部方法来执行以下操作:
cout << my_name[1:5] << endl;
Output: nAFl
更新 1:我尝试使用如下字符串类型
#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
如果您坚持使用 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"
}
如果您使用 std::string
(C++ 方式),您可以
std::string b = a.substr(1, 4);
如果您想要字符串的副本,则可以使用迭代器或 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);
是否可以实现一种方法,通过该方法我可以使用 :
运算符在 C++ 中进行切片。
比如我定义了一个C风格的字符串,如下所示:
char my_name[10] {"InAFlash"};
我能否实现一个函数或覆盖任何内部方法来执行以下操作:
cout << my_name[1:5] << endl;
Output:
nAFl
更新 1:我尝试使用如下字符串类型
#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
如果您坚持使用 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"
}
如果您使用 std::string
(C++ 方式),您可以
std::string b = a.substr(1, 4);
如果您想要字符串的副本,则可以使用迭代器或 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);