c++ - 如何从 C++ 中的字符串返回子字符串?
问题描述
我需要在 C++ 中实现类似 python 的切片方法。如果他们问我:
Slice("Hello World!",1) output = "ello World!"
Slice("Hello World!",0,5) output = "Hello"
Slice("Hello World!",0,-1) output = "Hello World"
Slice("Hello World!",3,-2) output = "lo Worl"
Slice("Hello World!",-5,-2) output = "orl"
Slice("Hello World!",14) output = " "
如果我的约束是这样的,我将如何实现这个类似切片的方法
到目前为止,我已经尝试创建一个 forloop。我尝试创建一个空字符串并尝试附加所需的索引,但我不明白如何。
解决方案
使用std::string::substr()
方法,例如:
std::string Slice(const std::string &str, ssize_t start, ssize_t end)
{
return str.substr(start, end-start);
}
如果你不能使用substr()
(出于某种荒谬的原因),那么你可以使用更像这样的东西:
std::string Slice(const std::string &str, ssize_t start, ssize_t end)
{
if (start >= str.length())
return std::string();
if (end > str.length())
end = str.length();
return std::string(str.c_str() + start, end - start);
}
推荐阅读
- python - 访问字段更新的时间(Django 模型)
- java - OptaPlanner:使计划实体链接起来并且可以为空
- ionic-framework - 如何使用预先保存的卡详细信息来填充 squareup SQpayment 表单
- javascript - div显示/隐藏不起作用?
- office365 - Outlook Web 加载项 - 在 Outlook 客户端中获取和设置会议室
- java - 在后台 java 控制台应用程序上打印字母 X
- sql - 在 postgresql 查询中需要拆分行的帮助
- kubernetes - 在 Helm 图表中编写自定义函数
- css - 导航选项卡上的 CSS 形状
- ubuntu-16.04 - 无法在 Ubuntu 服务器上安装 docker