使用命令 std::string::substr 将字符串拆分为C++
Split the string in C++ using command std::string::substr
我能够得到字符串的前半部分:
insert1 = tCreatureOne.substr(0, (tCreatureOne.length) / 2
我不知道如何获得字符串的后半部分
insert2 = tCreatureOne.substr((tCreatureOne.length) / 2), ?????)
这是我的代码。
// Insert creature two in to the
//middle of creature one.Science!
// Hamster and Emu make a HamEmuster
std::string PerformScience(std::string tCreatureOne, std::string tCreatureTwo)
{
std::string insert1;
std::string insert2;
std::string insert3;
// first half : 0 to middle
insert1 = tCreatureOne.substr(0, (tCreatureOne.length) / 2);
// last half: from middle to the end
insert2 = tCreatureOne.substr((tCreatureOne.length) / 2), tCreatureOne.length);
insert3 = insert1 + tCreatureTwo + insert2;
return insert3;
可能最重要的开发人员技能是知道如何进行在线研究。谷歌搜索"c ++ substr"显示这是最重要的结果:http://www.cplusplus.com/reference/string/string/substr/
在描述参数的部分中,len
描述如下:
要包含在子字符串中的字符数(如果字符串较短,则使用尽可能多的字符)。
字符串::npos 的值指示字符串末尾之前的所有字符。
所以你可以写:
insert2 = tCreatureOne.substr(tCreatureOne.length() / 2), std::string::npos);
但是,请注意,substr
声明如下:
string substr (size_t pos = 0, size_t len = npos) const;
意思是len
非常方便地默认为 npos
.
因此,您可以更简单地编写:
insert2 = tCreatureOne.substr(tCreatureOne.length() / 2));
但是,即使substr
没有指定"字符串的其余部分"的方便方法,您仍然可以轻松地按如下方式计算它:
int totalLength = tCreatureOne.length();
int firstLength = totalLength / 2;
int remainderLength = totalLength - firstLength;
//So...
insert2 = tCreatureOne.substr(tCreatureOne.length() / 2), remainderLength);
πάντα ῥεῖ 在他们的注释中是正确的 - 要检索字符串的后半部分,您无需指定第二个参数(字符串的末尾):
insert2 = tCreatureOne.substr(tCreatureOne.length() / 2);
上面的行将正常工作。另外,由于您使用的是 std::string
,请记住将括号添加到length()
调用中。
相关文章:
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 将字符串拆分为等长 c++ 的部分
- 如何使用 Boost C++ 打印第 n 个字符串拆分?
- 我在将字符串拆分为向量时遇到困难
- C++ 如何将字符串拆分为单个字符
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何将字符串拆分为一组 3 个字符,它们之间有空格
- 将字符串拆分为单个单词并将它们放置在向量中
- 基于其中的数字子字符串拆分字符串
- 如何在C++中将数字字符串拆分为数组
- 如何在 c++ 中将字符串拆分为字符串 2d 数组数组
- 如何将标准::字符串拆分为标准::string_views的范围 (v3)
- 将特定格式的字符串拆分为浮点数和字符串
- 在 c++ 中将字符串拆分为单独的变量
- 用C 中的4个字符将字符串拆分
- 如何用Arduino中的另一个字符串将字符串拆分
- 如何在 Main 方法之外将字符串拆分为标记
- C 将字符串按空白空间将字符串拆分,除非将其封闭在引号中并存储在向量中
- 将字符串拆分为矢量 C++
- 试图将字符串拆分为两个整数