21xrx.com
2024-09-20 00:50:45 Friday
登录
文章检索 我的文章 写文章
C++中的substr函数返回空字符串
2023-06-22 10:05:46 深夜i     --     --
C++ substr函数 空字符串 返回

在C++中,substr()函数是一个非常常用的字符串截取函数。通过这个函数,我们可以截取字符串的一部分,然后把它们赋值给新的字符串或者输出。但有时候,使用substr()函数可能会返回一个空字符串,这是为什么呢?

其实,substr()函数返回空字符串的问题并不是函数本身的问题,而是我们可能没有正确使用它。在下面的例子中,我们来看一下什么情况下substr()函数会返回空字符串:


#include <iostream>

#include <string>

using namespace std;

int main () {

 string str = "Hello World!";

 string sub = str.substr(20, 15);

 cout << "sub = " << sub << endl;

 return 0;

}

上面的代码中,我们尝试从字符串“Hello World!”的第20个位置开始截取15个字符,这显然是不行的,因为原字符串只有12个字符。于是substr()函数返回了一个空字符串给新的字符串sub。

如果我们需要得到正确的字符串,应该这样写:


#include <iostream>

#include <string>

using namespace std;

int main () {

 string str = "Hello World!";

 string sub = str.substr(6, 5);

 cout << "sub = " << sub << endl;

 return 0;

}

这时,我们从原字符串的第6个位置开始截取5个字符,得到字符串“World”。

除了上面的情况,substr()函数还有其他的参数使用问题可能导致返回空字符串。因此,在使用substr()函数时,我们一定要注意参数的设置。只有正确设置了参数,才能得到正确的截取字符串。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章