初始检查以查看子字符串是否在范围内

Initial Check to see if a Substring is within range

本文关键字:字符串 是否 范围内 检查      更新时间:2023-10-16

我正处于学习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