初始检查以查看子字符串是否在范围内
Initial Check to see if a Substring is within range
我正处于学习C++的开始,我想知道是否有一种方法可以断言可以从给定范围的字符串创建子字符串。我的字符串每次迭代的大小都会有所不同。我正在尝试从该原始字符串创建六个子字符串。由于大小的这种变化,我有时会尝试访问该特定迭代不存在的字符串索引。
例如,如果迭代 1 中的字符串是 11 个字符 我的第一个子字符串来自 3 个字符 - 有效 我的第二个子字符串是接下来的 3 个字符 - 有效 我的第三个子字符串是接下来的 5 个字符 - 有效 我的第四个子字符串是接下来的 4 个字符 - 无效 - 崩溃程序 我的第五个子字符串 - 无效,超出范围 我的第六个子字符串 - 无效,超出范围
我想知道是否可以做一个小检查来断言长度是有效的。值得注意的是,我想,我没有为这些子字符串设置任何默认值。它们被声明为:
字符串子 S1 字符串子S2 字符串子S3 ... ... 字符串子S6
在声明时将所有 6 个子字符串设置为 null 是否会缓解此问题,并且对于任何有效的子字符串,该值将被覆盖?
提前致谢
subS1 = str.substr(0, 3); // Could be valid range
subS2 = str.substr(3, 3); // Could be valid range
subS3 = str.substr(6, 5); // Could be valid range
subS4 = str.substr(11, 4); // Could be valid range
subS5 = str.substr(15, 4); // Could be valid range
subS6 = str.substr(19); // from the nineteenth character to the end
算法--->
步骤 1:以可变大小获取当前迭代中字符串的长度。
第 2 步:在迭代中编写此代码。
int i=0;
i= str.substr(start,end).length();
if( i>size) then,
std::cout<<"index exceeded";
要么在提取字符串之前检查str
的大小,要么依赖 std::string::substr 的len
参数:
要包含在子字符串中的字符数(如果字符串是 较短,使用尽可能多的字符)。值为 字符串::NPOS 指示字符串末尾之前的所有字符。
例:
#include <iostream>
#include <string>
int main ()
{
std::string str="Alexander the Great";
std::string str2 = str.substr (16, 25);
std::cout << str2 << 'n'; // eat
return 0;
}
它不会崩溃,它只会使用尽可能多的字符。
但是:
std::string str2 = str.substr (20, 25);
应该崩溃,所以在这种情况下这样做:
std::string str2 = ""; // initialise to empty string, that is the NULL you are saying I guess
if(str.size() > 20)
str2 = str.substr (20, 25);
// 'str2' will be an empty string
相关文章:
- C++-字符串是否包含一个带有简单循环的单词
- 将常量字符串添加到非常量字符串是否会给出常量字符串
- 检查字符串是否"null" C++
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 检查字符串是否为整数
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 如何检查字符串是否正确以将其转换为 int?
- 程序检查字符串是否只包含 1 和 0?
- 检查字符串是否是拉平德罗姆
- 尝试使用 indexOf 创建一个 if 语句来检查字符串是否包含字符.有一点麻烦
- 通过默认复制构造函数比较 C++ 字符串是否会影响性能,原因为何?
- gtest:检查字符串是否等于两个字符串之一
- 如何检查字符串是否包含所有这些:数字、字母和特殊字符
- 如何检查字符串是否以C++中的"ed"结尾;
- 字符串是否在其构造函数中复制数据
- 检查字符串是否是数字,然后将该数字转换为 int?
- 如何检查一个字符串是否包含多个其他字符串?
- 检查字符串是否仅包含字母
- 如何根据一个特定字母的出现来确定两个字符串是否相等?
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法